简体   繁体   中英

React Native Redux: not re-render FlatList after data changed

I'm making an application, a chat, and I need that when the push comes - the data appeared on the screen. For data I use Redux. Here is my code

Action:

export const newMsg = (item, disgussion_id) => {
    return {
        type: NEW_MESSAGE,
        payload: {
            item,
            disgussion_id
        }
    }
}

Reducer

const initialState = {
  messages: {},
}

...

    case NEW_MESSAGE:
      const message = {...state.messages}
      const arr = message[action.payload.disgussion_id]
      let exitDate = false
      console.log('[New push message]', action.payload.item)
      Object.keys(arr).map(e => {
        if (arr[e].date === action.payload.item.date) {
          arr[e].messages.unshift(action.payload.item)
          exitDate = true
        }
      })
      if (!exitDate) {
        arr.unshift({
          'date': action.payload.item.date,
          'messages': [action.payload.item]
        })
      }
      message[action.payload.disgussion_id] = arr

      return {
        ...state,
        messages: message
      }

Chat.js

const messages = useSelector(state => state.message.messages[route.params.uid]);

...

          {
                messages && <FlatList
                data={messages}
                renderItem={({item, index}) => {
                    return (<Message
                      date={item.date}
                      contacts={mainContacts}
                      item={item}/>)
                }}
                keyExtractor={(item, index) => String(index)}
                inverted={-1}
                initialScrollIndex={0}
                style={styles.bodyChat}
                refreshControl={<RefreshControl refreshing={refreshing} onRefresh={onRefresh}/>}
              />
            }

And when I change the data - the new data does not appear in the FlatList. What am I doing wrong?

My root reducer

const rootReducer = combineReducers({
    system: persistReducer(persistConfig, systemReducer),
    feed: persistReducer(persistConfig, feedReducer),
    message: persistReducer(persistConfig, messageReducer),
})

Looks like your state contains messages but you are trying to get state.message.messages .

if you change to this it should be able to get the new list

const messages = useSelector(state => state.messages[route.params.uid]);

Might be helpful if you provide your state structure for that reducer as there might be some other issues.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM