Is there a way I can wait for redux to obtain a state before my component is rendered? I have a function that helps me obtain a single product from my backend, this way when users want to update product details, the values are already pre-populated in the form. However when the app gets loaded the first and I do an useSelector to get the single product I firstly get "undefined" and then I get the product from the redux state. This causes the form values to be initially undefined, hence an error.
我希望总是有来自状态的值,而不需要未定义.在我的组件上,我有一个"useEffect"来调度一个函数以获取产品,它从url参数获取slug以将其发送到操作:
useEffect(() => {
dispatch(getSingleProduct(slug));
}, [dispatch, slug]);
这是获取项目的操作函数:
export const getSingleProduct = (slug) =>{
return async (dispatch) =>{
try {
const {data} = await axios.get(`${process.env.REACT_APP_API}/product/${slug}`);
dispatch(singleProd(data));
} catch (error) {
console.log(error)
}
}
}
const singleProd = data =>({
type: '[PROD] GET SINGLE PRODUCT',
payload: data
})
我能做些什么来保证产品始终可用吗?没有先定义?