简体   繁体   中英

React Native, Redux and Navigation: handling state updates when passing params from navigation

I have an app with a component which maps an array of posts (records, rows or whatever you like) from a redux slice into buttons to navigate to a detail component, the navigate action passes the post param so the detail component receives it.

// ParentComponent.js
// Redux selector
const posts = useSelector((state) => state.posts);

// The array is mapped like this
posts.map((post, index) => {
  return (
    <TouchableOpacity
      onPress={() => {
        navigation.navigate('TabNavigation', {
          screen: 'PostEditor',
          params: {post},
        });
      }}
      key={Post.slug}
      <PostDetail post={post} />
    </TouchableOpacity>
  );
});

A post view is composed by a large form, so I had to make the detail component divided into sections (child components), this means I'm passing down the received param to the child components:

// Detail View / PostEditor
const {post} = route.params;

return (
    <SafeAreaView>
      <ScrollView>
        <View style={styles.block}>
          <PostFormOne post={post} />

          <PostFormTwo post={post} />

          <PostFormThree post={post} />

          <PostFormFour post={post} />
        </View>
      </ScrollView>
    </SafeAreaView>
);

The problem is when I make a change to the redux store on every child component, the other components are not updated, I guess because the child components are referencing the navigation param post and not the redux post store.

If so, then my question is how would you reference the redux store using the navigation param?

If this is not correct then what would be a better approach to this functionality?

Thanks in advance.

you create another store variable for the selected post along with an action that updates the current post. Then in your TouchableOpacity onPress, you call the action to update the current post.

    <TouchableOpacity
      onPress={() => {
        navigation.navigate('TabNavigation', {
          screen: 'PostEditor',
        });
       dispatch(updateCurrentPost(post));
      }}
      key={Post.slug}
      <PostDetail post={post} />
    </TouchableOpacity>

This way, you don't need to pass the post at all, and just do:

useSelector((state)=> state.currentPost);

in all of your sub components. You will need to call the updateCurrentPost action in all your sub components to keep the current post in sync.

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