我有一个组件,我根据数据调用从API获取结果的操作:
按下此组件:
在componentWillMount上调用fetchProducts()函数。
以下功能称为:
function matchDispatchToProps(dispatch){
return bindActionCreators({selectLocation: selectLocation, fetchProductsHomeFromAPI: fetchProductsHomeFromAPI}, dispatch);
}
mapDispatchToProps是这样的:
var FETCHING_PRODUCTS="FETCHING_PRODUCTS";
var FETCHING_PRODUCTS_SUCCESS = "FETCHING_PRODUCTS_SUCCESS";
var FETCHING_PRODUCTS_FAILURE = "FETCHING_PRODUCTS_FAILURE";
var API = "https://api.abcd.in/get-home-products";
export function fetchProductsHomeFromAPI(data) {
return (dispatch) => {
dispatch(getProducts())
fetch(`${API}`, {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify({
city: data.city
})
})
.then(res =>res.json())
.then(json =>dispatch(getProductsSuccess(json.results)))
.catch(err => dispatch(getProductsFailure()))
}
}
function getProducts() {
return {
type : FETCHING_PRODUCTS,
}
}
function getProductsSuccess(data) {
return {
type : FETCHING_PRODUCTS_SUCCESS,
data
}
}
function getProductsFailure( ) {
return {
type : FETCHING_PRODUCTS_FAILURE,
}
}
行动如下:
import {combineReducers} from 'redux';
import LocationReducer from './reducer-location';
import ActiveLocationReducer from './reducer-active-location';
import productsHome from './reducer-products-home';
export default combineReducers({
location: LocationReducer,
activeLocation: ActiveLocationReducer,
productsHome : productsHome,
})
联合收割机减速机是:
import { persistStore, autoRehydrate } from 'redux-persist'
import { Provider } from 'react-redux';
import {createStore, compose } from 'redux';
import combineReducers from './src/Redux/reducers/combineReducers';
const store = compose(autoRehydrate())(createStore)(combineReducers)
persistStore(store, {storage: AsyncStorage}, () => {
console.log(store);
})
export default class MyApp extends Component {
render() {
return (
<Provider store = {store}>
<App />
</Provider>
);
}
}
在index.android.js商店中是这样的:
#set-location "MyDirectory"
dir -recurse | ?{ $_.PSIsContainer } | %{ Write-Host $_.FullName
(dir $_.FullName | Measure-Object).Count }
我收到此错误操作必须是普通对象。使用自定义中间件进行异步操作。
请帮我理解这个错误。 我无法将数据传递给我的操作吗?
另一个问题是,我可以在此操作中使用其他操作数据吗?
答案 0 :(得分:2)
我们可以做的是
import * as loginAction from '../../actions/login';
fetchProducts(){
var city = 'ABCD';
this.props.fetchProductsHomeFromAPI(city);
}
const mapDispatchToProps = dispatch => ({
fetchProductsHomeFromAPI: (city) => dispatch(loginAction.sendToken(city),
});
这是我已经定义了动作的动作文件(动作/登录)
import { createAction } from 'redux-actions';
function checkdispatch(data) {
return createAction(constant.OPEN_USER_DRAWER)(data);
}
**value will be there in the sendToken function **
export function sendToken(city) {
console.log(city)
**here will call you API**
dispatch(checkdispatch(true));
}
希望这会帮助您获得行动价值