需要帮助以简化器函数内部编写的函数获取响应
功能组件
STRING
在我的减速器中
import {
getAssets,
} from '../../reducers';
const myFunctionalComponent = (props) => {
const dispatch = useDispatch();
const onLinkClick = () => {
dispatch(getAssets());
}
}
return (
<div>
<mainContent />
</div>
)
}
当我单击链接时,我需要在reducer中调用我的api并在开发人员控制台的newtwork选项卡中获取它的响应,但是如何在我的功能组件中获取响应(即successToast,data,isLoading)并将相同的内容传递给子组件?
答案 0 :(得分:0)
我建议您更改项目的结构。将所有网络呼叫都放在一个文件中,然后从您的组件中调用它们。更好的可读性和可理解性
import {
getAssets,
} from './actions';
const myFunctionalComponent = (props) => {
const dispatch = useDispatch();
const onLinkClick = async () => {
const data = await dispatch(getAssets());
}
}
return (
<div>
<mainContent />
</div>
)
}
在./actions.js
中const getAssets =()=>async dispatch =>{
const res = await axios.get();
dispatch(setYourReduxState(res.data));
return res.data;
}
现在,您的组件将获取网络通话数据。并且您的redux状态也将得到更新
答案 1 :(得分:0)
对于功能组件,要访问集中存储在redux中的状态,您需要使用useSelector
中的react-redux
钩子
import React from 'react'
import { useSelector } from 'react-redux'
export const CounterComponent = () => {
const counter = useSelector(state => state.counter)
return <div>{counter}</div>
}
官方文档: https://react-redux.js.org/api/hooks#useselector-examples
还找到了这个工作示例供您参考。