[英]How can I make an action be reusable? ReactJS with Redux
I need to do a dynamic action.我需要做一个动态的动作。 In other words, it can be reused for differents actions.
换句话说,它可以重复用于不同的操作。
I tried to create a function that loads type and payload, but an error appears.我尝试创建一个加载类型和有效负载的 function,但出现错误。
I'm trying make this function works:我正在尝试使这个 function 工作:
export function getData(url, type) {
const request = Server.get(url)
return (dispatch) =>
request.then((response) => {
dispatch({
type: type,
payload: response.data
})
}).catch(function (error) {
console.log(error)
});
}
But I got an error when I call this function this way:但是当我以这种方式调用此 function 时出现错误:
export function getClientes() {
Actions.getData('ClientesEFornecedores', GET_CLIENTES)
}
It's showing:它显示:
Uncaught Error: Actions must be plain objects. Use custom middleware for async actions.
I'm Calling the getClientes() function this way:我这样调用 getClientes() function :
function ClientesTable(props)
{
const dispatch = useDispatch();
const clientes = useSelector(({erpCliente}) => erpCliente.clientes.data);
useEffect(() => {
dispatch(Actions.getClientes());
}, [dispatch]);
How can I make an action be reusable?如何使动作可重用?
Try something like this尝试这样的事情
export const getData=(url, type) =>async dispatch=>{
try{
const response = await Server.get(url);
dispatch({ type: type,payload: response.data })
} catch(err){
console.log(err)
}
}
getClientes function getClientes function
export const getClientes=() => dbActions.getData('ClientesEFornecedores', GET_CLIENTES);
In fact I had almost succeeded.事实上,我几乎成功了。 All that remained was to return the function call.
剩下的就是返回 function 调用。
This is the way that works:这是有效的方式:
export function getClientes() {
return dbActions.getData('ClientesEFornecedores', GET_CLIENTES)
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.