不知道如何使用钩子正确访问 redux 状态的获取结果



我正试图从我的后端将数据提取到我的redux存储中,然后在我的功能React组件中访问它。(使用钩子而不是类(

当我试图在组件本身中获取数据时,如下所示:

useEffect(() => {
const fetchCategories = async () => {
const res = await trees.get('/categories')
setCategories(res.data)
}
fetchCategories()
}, [])

它是有效的,我可以访问数据,但它显然不在redux存储中,只是在我的组件状态中。(我在一个单独的文件中创建了axios,所以我可以用tree.get获取(

获取我的动作创建者也能工作,我可以成功地将响应数据发送到我的redux存储中,如下所示:

export const fetchCategories = async () => {
const res = await trees.get('/categories')
dispatch({ type: FETCH_CATEGORIES, payload: res.data })
}

我的redux存储中的状态

但我不知道如何正确地运行我的动作创建者,而不是从我的React组件访问redux存储中的数据。我尝试了几种方法,比如:

const [categories, setCategories] = useState([{
"value": "loading...",
"icon": "music"
}])
useEffect(() => {
const plsWork = async () => {
const res = await fetchCategories()
console.log(res)
}
plsWork()
}, [])

或者redux中的useSelector Hook,但我想不出办法,这很有效。:(

您也必须传递dispatch,因为您只能在功能组件中使用useDispatch钩子。因此:

export const fetchCategories = async ()=> (dispatch)=> {
const res = await trees.get('/categories')
dispatch({ type: FETCH_CATEGORIES, payload: res.data })
}

然后在您想要访问状态的组件中,您应该使用useSelector挂钩

const dispatch=useDispatch(); 
const categories=useSelector((state)=>state.reducerName.categories); // if you have more than one reducer write here reducername which you have assigned it in the combineReducer or if you are using only single reducer then you can also access it simply by state.categories
useEffect(() => {

dispatch(fetchCategories());


}, [])

您使用useDispach钩子来更新redux存储数据,您应该使用useSelector钩子来获取所需的状态数据。

const categories = useSelector((state) => state.categories)

最新更新