gpt4 book ai didi

javascript - 不知道如何使用钩子(Hook)在 redux 状态下正确访问获取结果

转载 作者:行者123 更新时间:2023-12-05 02:32:16 26 4
gpt4 key购买 nike

我正在尝试从我的后端获取数据到我的 redux 存储,而不是在我的功能性 React 组件中访问它。 (使用钩子(Hook)而不是类)

当我尝试像这样在组件本身中获取数据时:

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

fetchCategories()
}, [])

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

并且在我的 action creator 中获取也能正常工作,我可以像这样成功地将响应数据发送到我的 redux 存储中:

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

state in my redux store

但我不知道如何正确运行我的 action creator,而不是从我的 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 钩子(Hook)。所以为此:

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

然后在你想要访问状态的组件中你应该使用 useSelector hook

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());



}, [])

关于javascript - 不知道如何使用钩子(Hook)在 redux 状态下正确访问获取结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71307257/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com