React Native Flatlist extraData 不起作用 redux 数据已更改



我在 redux 中有数组。我正在显示平面列表上的数据。但是,当我编辑数组数据时,平面列表不会重新渲染。我该如何解决这个问题?我检查了我的 redux 并且工作正常

this.props.notes[this.state.Index]={
color: JSON.stringify(BgColor),
date: this.state.fullDate.toString(),                    
note: this.state.noteText,
name: this.state.noteName,
type: "note",
noteID:this.props.notes[this.state.Index].noteID
}
this.props.editNotes(this.props.notes);

平面列表代码;

<FlatList
ref={(list) => this.myFlatList = list}           
data={this.props.notes}
showsVerticalScrollIndicator={false}
renderItem={({item, index})=>(
)}
removeClippedSubviews={true}  
extraData={this.props.notes}   
/>

mapStateToProps 与 Flatlist 在同一页面上

const mapStateToProps = (state) => {
const { notes } = state
return { notes }
};

还原剂

const notes = [];
const notesReducer = (state = notes, action) => {
switch (action.type) {
case 'editNotes':
return state = action.payload;
default:
return state
}
};
export default notesReducer;

它不更新的原因是因为你没有返回一个新数组。引用是相同的。

返回更新的状态,如return [...state,action.payload]

它没有正确更新数据的原因是因为突变。

有问题的代码是这部分。

this.props.notes[this.state.Index]={
color: JSON.stringify(BgColor),
date: this.state.fullDate.toString(),                    
note: this.state.noteText,
name: this.state.noteName,
type: "note",
noteID:this.props.notes[this.state.Index].noteID
}
this.props.editNotes(this.props.notes);

应该是这样

const { notes, editNotes } = this.props; 
const newNotes = [...notes];
const { index } = this.state;
newNotes[index] = {
//update data
} 
editNotes(newNotes);

您可以通过多种方式解决问题,但我在您的代码中看到的错误部分是 Reducer。根据标准,您的减速器应该是纯函数,并且状态不应发生变化。

const notes = [];
const notesReducer = (state = notes, action) => {
switch (action.type) {
case 'editNotes':
return {
...state,
...action.payload;
},
default:
return state
}
};
export default notesReducer;

这应该可以解决您的问题。

建议: 尝试在 redux 中创建嵌套层次结构,例如

const initialState = {
notes: [],
};
const notesReducer = (state = initialState, action) => {
switch (action.type) {
case 'editNotes':
return {
...state,
notes: [
...state.notes,
...action.payload.notes,
],
},
default:
return state
}
};
export default notesReducer;

最新更新