我是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);
只有一个数组时,它首先起作用。像这样
INITIAL_STATE = { 编号:1 问题:“纪录片”, 答案:[ {id:“ 1”,文字:“记录映画”}, {id:“ 2”,文字:“理科”}, {id:“ 3”,文字:“自由”}, {id:“ 4”,文字:“形”} ], 名称:0 }
但是添加更多的数组并更改操作和reducer之后,才可以。这是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)
答案 0 :(得分:1)
似乎您不是要更新requirements.txt
道具,而只是将其设置为空字符串。另外,您可能会传递商品的requirements.txt
并将其用于查找:
name
答案 1 :(得分:1)
这应该有效。
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;
}
};