React Native Flatlist extraData无法正常工作Redux数据已更改

时间:2019-09-02 16:35:51

标签: reactjs react-native redux react-redux

我在redux中有数组。我在Flatlist上显示数据。但是,当我编辑数组数据时,平面列表不会重新呈现。我怎么解决这个问题?我检查了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与平面列表在同一页面上

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;

3 个答案:

答案 0 :(得分:1)

不更新的原因是因为您没有返回新的数组。参考是相同的。

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

答案 1 :(得分:1)

您可以通过多种方式解决此问题,但是我在代码中看到的错误部分是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;

答案 2 :(得分:0)

之所以不能正确更新数据是因为突变。

有问题的代码就是这部分。

            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);