gpt4 book ai didi

javascript - React Native Redux - 如何更新数组中的项目?

转载 作者:行者123 更新时间:2023-12-01 00:12:00 25 4
gpt4 key购买 nike

我是 React Native 和 Redux 的新手,现在正在构建一个测验应用程序。

我想更新数组中的项目(名称)。有人可以让我知道我的以下代码有什么问题吗:

export const setName = name => ({
type: "ADD_NAME",
id: 1,
name: name
});

INITIAL_STATE = [
{
id: 1,
question: "documentary",
answers: [
{ id: "1", text: "記録映画" },
{ id: "2", text: "理科" },
{ id: "3", text: "自由" },
{ id: "4", text: "形" }
],
name: 0
},
{
id: 2,
question: "cozy",
answers: [
{ id: "1", text: "居心地の良い" },
{ id: "2", text: "関係する" },
{ id: "3", text: "ブレーク" },
{ id: "4", text: "車" }
],
name: 0
},
{
id: 3,
question: "utmost",
answers: [
{ id: "1", text: "最大限" },
{ id: "2", text: "疑問に思う" },
{ id: "3", text: "昨日" },
{ id: "4", text: "まだ" }
],
name: 0
}
];

const reducer = (state = INITIAL_STATE, action) => {
switch (action.type) {
case "ADD_NAME":
return state.map((item, index) => {
if (item.id === 1) {
return {
...item,
name: ""
};
}
return item;
});

default:
return state;
}
};

export const reducers = combineReducers({
user: reducer
});

// store.js
export const store = createStore(reducers);

当只有一个数组时,它首先起作用。像这样

初始状态={ 编号: 1, 问题:“纪录片”, 答案:[ { id: "1", text: "记录映画"}, { id: "2", text: "理科"}, { id: "3", text: "自由"}, { id: "4", 文本: "形"} ], 姓名:0 }

但在添加更多数组并更改操作和化简器后,情况就不再这样了。这是 Home.js 的其余代码(容器+组件)

export class Home extends Component {
render() {
return (
<View style={{flex: 1, justifyContent: 'space-around', alignItems: 'center'}}>
<Text style={{marginTop: 100}}>My name is {this.props.name}.</Text>
<View style={{flexDirection: 'row'}}>
<Button
onPress={() => this.props.setName(1)}
title="setName"
/>
<Button
onPress={() => this.props.setName('2')}
title="setName"
/>
</View>
<Text style={{marginBottom: 100}}>現在のstore: {JSON.stringify(store.getState())}</Text>
</View>
)
}
}

const mapStateToProps = state => ({
name: state.user.name
})

const mapDispatchToProps = {
setName,
deleteName
}

export default connect(
mapStateToProps,
mapDispatchToProps
)(Home)

最佳答案

这应该有效。

const reducer = (state = INITIAL_STATE, action) => {
switch (action.type) {
case "ADD_NAME":
const { id = 1, name = "" } = action;
return state.map(item => ({
...item,
name: item.id === id ? name : item.name
}));
default:
return state;
}
};

关于javascript - React Native Redux - 如何更新数组中的项目?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60017832/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com