[英]React functional components with hooks - getting response from function written in reducer
需要帮助才能从减速器 function 内部编写的 function 获得响应
功能组件
import {
getAssets,
} from '../../reducers';
const myFunctionalComponent = (props) => {
const dispatch = useDispatch();
const onLinkClick = () => {
dispatch(getAssets());
}
}
return (
<div>
<mainContent />
</div>
)
}
在我的减速机中
const reducer = (state = initialState, action) => {
switch (action.type) {
case ASSETS_LIST: {
return {
...state,
successToast: true,
isLoading: false,
data: action.payload,
};
}
}
export const listsDispactcher = () => dispatch => {
dispatch({ type: SHOW_LOADER });
performGet(ENDPOINT URL)
.then(response => {
debugger;
const payload = response.data;
dispatch({
type: ASSETS_LIST,
payload: {
...payload,
data: payload.results,
},
});
dispatch({ type: HIDE_LOADER });
})
.catch(err => {
dispatch({ type: GET_ASSETS_ERROR, payload: err });
);
});
};
当我单击链接时,我在减速器中的 function 中调用了我的 api 并在开发人员控制台的 newtwork 选项卡中得到响应,但是如何在我的功能组件中获取响应(即 successToast,data,isLoading )并传递相同的子组件?
我建议您更改项目的结构。 将所有网络调用放在一个文件中,然后从您的组件中调用它们。 更好的可读性和可理解性
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 state 也将获得更新
对于功能组件,要访问集中存储在 redux 中的 state,您需要使用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
还找到了这个工作示例供您参考。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.