如何使用API响应设置useReducer初始状态



我是React的新手,正在尝试构建一个具有cart功能的应用程序,用户可以在其中向cart添加机器人。我使用Context API在应用程序中提供cart,使用useReducer提供状态。机器人是从服务器上取出来的,加载得很好。但我似乎找不到一种方法来使用提取的产品设置reducer的初始状态。该状态总是为机器人返回一个空数组。如何解决这个问题?

const CartProvider = ({ children }) => {
const [robots, setRobots] = useState([]);
useEffect(() => {
fetch('http://localhost:8000/api/robots')
.then(res => res.json())
.then(data => setRobots(data?.data))
}, [])
const initialState = {
robots: [...robots],
cart: []
}
const [state, dispatch] = useReducer(cartReducer, initialState);
return (
<CartContext.Provider value={{ state, dispatch }}>
{children}
</CartContext.Provider>
);
}
export default CartProvider;

由于初始状态值是异步获取的,因此需要调度一个操作来设置state值。

示例:

const cartReducer = (state, action) => {
switch(action.type) {
... other reducer cases ...
case 'INITIALIZE_CART': 
return action.payload;
default:
return state;
}
};

CartProvider

const initialState = {
robots: [],
cart: []
};
const CartProvider = ({ children }) => {
const [robots, setRobots] = useState([]);
const [state, dispatch] = useReducer(cartReducer, initialState);
useEffect(() => {
fetch('http://localhost:8000/api/robots')
.then(res => res.json())
.then(data => {
dispatch({
type: 'INITIALIZE_CART',
payload: {
...initialState,
robots: data?.data,
}
});
});
}, []);
return (
<CartContext.Provider value={{ state, dispatch }}>
{children}
</CartContext.Provider>
);
};

通常还会在应用程序初始化状态中保留一些状态。UI根据此状态值进行有条件渲染。

示例:

const initialState = {
initialized: false,
robots: [],
cart: []
};

const cartReducer = (state, action) => {
switch(action.type) {
... other reducer cases ...
case 'INITIALIZE_CART': 
return {
...action.payload,
initialized: true,
};
default:
return state;
}
};
const [state, dispatch] = useReducer(cartReducer, initialState);

useReducer不会监视对initialState的更改,它只会考虑其初始值。一旦获取数据,您就可以调度一个操作来更新状态。

const initialState = {
robots: [],
cart: []
}
const CartProvider = ({ children }) => {
const [state, dispatch] = useReducer(cartReducer, initialState);
useEffect(() => {
fetch('http://localhost:8000/api/robots')
.then(res => res.json())
.then(data => {
// dispatch action to update the reducer state 
})
}, [])

return (
<CartContext.Provider value={{ state, dispatch }}>
{children}
</CartContext.Provider>
);
}
export default CartProvider;

如果嵌套组件在填充状态之前不能正常工作,则可以有条件地渲染children:

return (<CartContext.Provider value={{ state, dispatch }}>
{state?.robots?.length > 0 && children}
</CartContext.Provider>);

相关内容

  • 没有找到相关文章