[英]react props comes blank on first transaction
I am using redux promise middleware.我正在使用 redux promise 中间件。 I am trying to pass the value in Propsx to state.我正在尝试将 Propsx 中的值传递给 state。 Props comes empty in useEffect.道具在 useEffect 中为空。 How can I transfer the contents of the props to state.如何将道具的内容转移到 state。 Props value comes next.接下来是道具价值。
action:行动:
export function fetchBasket() {
return dispatch => {
dispatch({
type: 'GET_BASKET',
payload: axios.get('url', {
})
.then(response => response.data)
});
};
}
reducer:减速器:
const initialState = {
fetching: false,
error: {},
basket: []
};
export default (state = initialState, { type, payload }) => {
switch (type) {
case types.GET_BASKET_PENDING:
return {
fetching: true
};
case types.GET_BASKET_FULFILLED:
return {
...state,
fetching: false,
basket: payload.result,
};
case types.GET_BASKET_REJECTED:
return {
fetching: false,
error: payload.result
};
default:
return state;
}
};
use in Component在组件中使用
useEffect(() => {
props.fetchBasket();
console.log(props.basket); // null :/
}, []);
useEffect(() => {
props.fetchBasket();
console.log(props.basket); // null :/
}, []);
Your props will update only in the next event loop cycle, to use react hooks data updation inside useEffect
you need to useReducer
https://reactjs.org/docs/hooks-reference.html#usereducer您的道具将仅在下一个事件循环周期中更新,要在useEffect
中使用 react hooks 数据更新,您需要useReducer
https://reactjs.org/docs/hooks-reference.html#usereducer
[enter link description here][1]If you want to have values in your first run(Mount). [在此处输入链接描述][1]如果您想在第一次运行(安装)中获得值。 fetch here ==> useLayoutEffect and this will gives the values in useEffect ()[]. fetch here ==> useLayoutEffect这将给出useEffect ()[] 中的值。 [uselayouteffect]: https://reactjs.org/docs/hooks-reference.html#uselayouteffect [uselayouteffect]: https://reactjs.org/docs/hooks-reference.html#uselayouteffect
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.