在redux thunk中分发后,是否有可能立即获得存储值? 我的组件是这样的: ...
const handleGetProduts = async() => {
await props.getProducts()
setResults(props.results)
console.log('props after getProducts: ', props)
}
... 减速器是:
const initialState= {
results: [],
products: [],
}
export default (state = initialState, action) => {
console.log(action)
switch (action.type) {
case 'GET_PRODUCTS_FULFILLED':
return {
...state, results: action.payload.results
}
default:
return state
}
}
export const getProducts = () => async dispatch => {
console.log('Enter getProducts')
const result = await dispatch({
type: 'GET_PRODUCTS',
payload: fetch('http://server.domaina.com').then(response => response.json())
});
return result;
};
谢谢
答案 0 :(得分:1)
在功能组件中,可以使用useSelector挂钩从存储中获取状态。
但是
1. console.log('props after getProducts: ', props)
不会立即打印最新产品,因为状态更新是异步的,并且您正在登录处理程序。要查看更新的产品,请将控制台日志放在功能组件中的某个位置。
handleGetProduts
不需要异步,也不需要等待props.getProducts()
。import React from 'react'
import { useSelector } from 'react-redux'
**useSelector ex**
export const ProductsComponent = () => {
const products = useSelector(state => state.products)
return <div>{products[0].name}</div>
}