我有一份客户名单。添加新客户端时,我希望操作创建者检查客户端名称是否已存在,如果存在,则显示错误。我用来查找具有该名称的客户端是否已经存在的filter()方法不起作用...我做错了什么?
行动:
export const addClient = (client) => {
return(dispatch, getState) => {
console.log('state: ' + JSON.stringify(getState()));
let clientList = getState().clientList;
console.log('clientList: ' + clientList);
if (clientList && clientList.map( client => {
return client.name;
}).includes(client.name))
{ return ( dispatch({type: 'ADD CLIENT ERROR'}) ) }
else { dispatch({type: 'ADD CLIENT', client}) }
}
}
减速器:
const initState = {
clientList: [],
clientErr: null,
};
const clientReducer = (state = initState, action) => {
switch (action.type) {
case 'ADD CLIENT ERROR':
console.log('add client failed');
return {
...state,
clientErr: 'A client with this exact name already exists, please try again.',
};
default:
return state;
}
};
export default clientReducer;
添加客户端的按钮工作正常,调度发送到操作,但这是我得到错误的地方。
更改逻辑以查找是否存在名称:
let clientList = getState().clientList
if (clientList && clientList.map( client => {
return client.name;
}).includes(client.name)
)
getState是一个Redux方法,在这里你试图通过点表示法访问对象属性。你在这里可以做的是从这个方法返回结构值,如下所示:
const {
clients: { clientsList },
} = getState();
然后在if语句中过滤它。