所以我正在构建一个应用程序,每次导航到页面时,我都会使用React Redux在Flatlist
中添加一个项目来更新列表,问题是平面列表的行为与我想象的不同,当我用.submitItem
按下按钮并导航到下一个屏幕时,平面列表不会更新数组并只显示我新添加的项目,它再次添加了相同的列表,同时显示了以前的列表和当前的列表,我发现很难解释,所以我希望下面的代码更清楚:
添加项目屏幕
class addItem extends Component {
constructor(props) {
super(props);
this.state = {
id: id,
name: name,
lastName: lastName,
list: this.props.list,
};
}
submitExercise(){
let list = this.state.list;
list.push({
id: id,
name: name,
lastName: lastName,
});
this.props.updateList(list);
this.props.navigation.navigate("ListItem");
}
render() {
return (
<Button onPress={this.submitExercise()}>Submit</Button>
)}}
function mapStateToProps(store){
return{
list: store.userState.list
};
}
const mapDispatchToProps = { updateList };
export default connect(mapStateToProps, mapDispatchToProps)( addItem );
项目列表屏幕
class ListItem extends Component {
constructor(props) {
super(props);
this.state = {
list: [],
}; }
static getDerivedStateFromProps(props, state) {
if (props?.list) {
return {
list: [...state.list, ...props.list],
};
}
return null;
}
render() {
return (
<FlatList
data={this.state.list}
renderItem={({ item }) => (
<View>
<Text>{item.name}</Text>
<Text>{item.lastName}</Text>
</View>
)}
keyExtractor={(item, index) => item.id}
/>
)}}
function mapStateToProps(store){
return{
list: store.userState.list
};
}
export default connect(mapStateToProps)(ListItem);
功能updateList
export const updateList = (list) => {
return { type: ADD_ITEM, payload: list}
}
请更改
<Button onPress={this.submitExercise()}>Submit</Button>
至
<Button onPress={this.submitExercise}>Submit</Button>
因为它在组件的挂载上执行submitExcercise函数,所以代码中的其他内容似乎也不错。