更新redux存储中对象数组元素的值
操作创建者在redux存储区的json数组中有一个挑战更新现有元素值。 你也可以在下面分享更新redux存储中对象数组元素的值,redux,react-redux,Redux,React Redux,操作创建者在redux存储区的json数组中有一个挑战更新现有元素值。 你也可以在下面分享 console.clear() const CreateTeam = (team, point) => { return { type:"CREATE_TEAM", payload: {team, point} } } const UpdateTeam = (team, point) => { return { type:"UPDATE_TEAM_POIN
console.clear()
const CreateTeam = (team, point) => {
return {
type:"CREATE_TEAM",
payload: {team, point}
}
}
const UpdateTeam = (team, point) => {
return {
type:"UPDATE_TEAM_POINT",
payload: {team, point}
}
}
const TeamReducer = (state = [], action) => {
if(action.type == "CREATE_TEAM")
{
return [...state, action.payload]
}
if(action.type == "UPDATE_TEAM_POINT")
{
let point=action.payload.point;
return [...state, {
...state.teams,
point:point
}]
}
return state;
}
const { createStore, combineReducers } = Redux;
const league = combineReducers({
teams: TeamReducer
})
const store = createStore(league);
store.dispatch(CreateTeam("TeamA",10));
store.dispatch(CreateTeam("TeamB",20));
store.dispatch(UpdateTeam("TeamA",15));//not work
console.log(store.getState())
创建动作效果很好,我希望TeamA的分值设置为15。。但其添加的新对象只有点属性值15actionTypes名称中存在错误: 行动分派类型:更新\u团队 reducer处理操作。类型==更新团队\u点 您必须执行不可变更改,请尝试以下操作: const TeamReducer=state=[],action=>{ ifaction.type==创建团队 { 返回[…状态、操作、有效负载] } ifaction.type==更新团队 { const{team,point}=action.payload; const changedIdx=state.findIndexitem=>item.team==team; 返回[…state.slice0,changedIdx,action.payload,…state.slicechangedIdx+1] } 返回状态; }
我还更新了我的答案,你没有正确地更新你的状态,你的状态中没有团队。效果很好,但我想知道这种更新存储的方式是否会触发使用该列表作为道具的react组件?你应该以某种方式连接react和redux世界。最好的方法是使用react-redux库。请参阅redxu文档中的本节: