我在这里学习redux。我提交输入时遇到问题。我有2个文本输入,我想将它存储在一个数组中,但是当我得到错误。看起来应用程序添加了一个新的未定义数据,因此我无法加载未定义的属性。但是当我在行动中使用一个参数时,它有效,我不知道为什么。这是我第一次使用redux,希望你能帮帮我,谢谢
actions.js
import { ADD_PERSON, DEL_PERSON} from '../constants';
export const addPerson = (person, age) => {
return {
type: ADD_PERSON,
person,
age
}
}
export const delPerson = (person, age) => {
return {
type: DEL_PERSON,
person,
age
}
}
我的减速机
import { ADD_PERSON, DEL_PERSON} from '../constants';
const initState = {people: [{ name: 'Wahyu', age: '18' }]}
export default function peopleReducer(state = initState, action){
switch (action.type) {
case ADD_PERSON:
return {
people: [
...state.people,
action.person,
action.age,
],
};
case DEL_PERSON:
return {
people: state.people.filter(p => p.name !== action.person.name),
};
default:
return state;
}
}
组件文件
state = {
name: '',
age: '',
}
addPerson = () => {
if (this.state.name === '') return;
this.props.dispatchAddPerson({
name: this.state.name,
age: this.state.age,
});
}
deletePerson = (person) => {
this.props.dispatchdeletePerson(person)
}
render() {
console.log(this.props.people)
return (
<View>
<Text style={styles.title}>People</Text>
<TextInput
onChangeText={(name) => this.setState({name})}
style={styles.input}
value={this.state.name}
placeholder="Name"
/>
<TextInput
onChangeText={(age) => this.setState({age})}
style={styles.input}
value={this.state.age}
placeholder="Age"
/>
<TouchableHighlight
underlayColor="#ffa012"
style={styles.button}
onPress={this.addPerson}
>
<Text style={styles.buttonText}>Add Person</Text>
</TouchableHighlight>
{
this.props.people.map((person, index) => (
<View key={index} style={styles.person}>
<Text>Name: {person.name}</Text>
<Text>Age: {person.age} </Text>
<Text onPress={() => this.deletePerson(person)}>Delete Person</Text>
</View>
))
}
</View>
)
}
}
function mapStateToProps(state) {
return{
people: state.people.people
}
}
function mapDispatchToProps (dispatch) {
return {
dispatchAddPerson: (person,age) => dispatch(addPerson(person,age)),
dispatchdeletePerson: (person) => dispatch(delPerson(person))
}
}
export default connect(
mapStateToProps,
mapDispatchToProps
)(App)
答案 0 :(得分:2)
你的减速机中的这行不正确
case ADD_PERSON
return {
people: [
...state.people,
action.person,
action.age, <---this is wrong
],
};
应该是
case ADD_PERSON
return {
people: [
...state.people,
action.person
],
};
行动可能如下:
export const addPerson = (person, age) => {
return {
type: ADD_PERSON,
Object.assign({}, person , {age}),
}
}