case UPDATE_CONVERSATION_ACTION:
var list = state.messageList ? state.messageList.length > 0 ? state.messageList : [] : [];
if(list.length > 0) {
let val = state.messageList.findIndex(e=>e.postId === action.payload[0])
if(val !== -1) {
var messageItem = {} as MessageListItem
var item = state.messageList[val];
var messages = item.messages;
messages.push(action.payload[1]);
messageItem.messages = messages
messageItem.postId = action.payload[0];
list[val] = messageItem
}else {
list.push({postId: action.payload[0],messages : [action.payload[1]]})
}
}
else {
list.push({postId: action.payload[0],messages : [action.payload[1]]})
}
return {
...state,
messages: [...state.messages, action.payload],
messageList :list
};
<FlatList
data={this.props.messagesList ? this.props.messagesList.length > 0 ? this.props.messagesList.find(e=> e.postId === this.state.postId)?.messages ?? [] : [] : []}renderItem={({ item }) => (
this.renderItems(item)
)}
// extraData={selected}
/>
现在我从套接字侦听数据,将数据调度并更新列表,但没有问题,因为它没有呈现我的平面列表组件,但它已更改。仅当我在输入中按下任何键时,才响应反应渲染组件
我确实做了类似的更改
var existMessageList = state.messageList.findIndex(e => e.postId === action.payload[0]);
return {
...state,
messageList : existMessageList !== -1 ? state.messageList.map((val,i)=> val.postId === action.payload[0] ? {...val, messages : state.messageList[i].messages.concat(action.payload[1])} : val) :
[...state.messageList,{postId : action.payload[0],messages : [action.payload[1]]}]
};
工作正常
答案 0 :(得分:1)
您正在使用所有.push()
和list[val] =
行来改变现有状态。请不要这样做。
有关如何正确编写不可变更新的信息,请参见the Redux docs page on "Immutable Update Patterns"和帖子The Complete Guide to Immutability in React and Redux。
我强烈建议您使用our official Redux Toolkit package。它具有configureStore
API,默认情况下会捕获突变,而createSlice
API实际上允许您编写“变异”逻辑,该逻辑可以安全地转换为正确的不可变更新。