21095

React Native: Hook Child State to Parent's State using Context

<h3>Question</h3>

I'm trying to rerender {userNumbers} in <em>ChildScreen</em>. I managed to add userNumbers state in <em>Home</em>, but it doesn't rerender the text.

UserContext.js

import { createContext } from 'react'; export const UserContext = createContext(null);

Home.js

import React from 'react'; import { createStackNavigator } from '@react-navigation/stack'; import { UserContext } from "../contexts/UserContext"; import ChildScreen from "ChildScreen"; const Stack = createStackNavigator(); export default function Home() { const [state, dispatch] = React.useReducer((prevState, action) => { switch (action.type) { case 'ADD_USER': return { ...prevState, users: state.users + action.newUsers }; } }, { users: 0 }); const userContext = React.useMemo( () => ({ addUsers: async data => { dispatch({ type: 'ADD_USER', newUsers: data.newUsers }); }, userNumbers: state.users }), [] ); return ( <UserContext.Provider value={userContext}> <Stack.Navigator> <Stack.Screen name="ChildScreen" component={ChildScreen} /> </Stack.Navigator> </UserContext> ) }

ChildScreen.js

import React from 'react'; import { View, Text } from 'react-native'; import { TouchableWithoutFeedback } from 'react-native-gesture-handler'; import { UserContext } from "../contexts/UserContext"; export default function ChildScreen() { const { addUsers, userNumbers } = React.useContext(UserContext); render ( <View><Text>{userNumbers}</Text></View> <TouchableWithoutFeedback onPress={() => { addUsers({newUsers: 999)}) }> <Text>Add 999 Users</Text> </TouchableWithoutFeedback> ) }
<h3>Answer1:</h3>

You need to re-create the userContext value when state.users change by adding state.users as a dependency to useMemo otherwise you context value will keep holding the same reference of value and will note trigger change for any listeners

const userContext = React.useMemo( () => ({ addUsers: data => { dispatch({ type: 'ADD_USER', newUsers: data.newUsers }); }, userNumbers: state.users }), [state.users] // Add a dependency here so that user update changes reference );

Also you should define your reducer to be pure, i.e it shouldn't use state from closure

const [state, dispatch] = React.useReducer((prevState, action) => { switch (action.type) { case 'ADD_USER': return { ...prevState, users: prevState.users + action.newUsers // use prevState here }; } }, { users: 0 });

P.S. You need not define addUsers function to be async. dispatch happens asynchronously but requires a re-render to take effect and you need not wait on it


<h3>Answer2:</h3>

You need to re-evaluate useContext on state.users change:

const userContext = React.useMemo( () => ({ //... userNumbers: state.users, }), [state.users] );

来源:https://stackoverflow.com/questions/62387281/react-native-hook-child-state-to-parents-state-using-context

Recommend

  • Self Signed SSL Certificate Use With Windows Server 2012, Bonobo Git Server
  • Send a string on Android with HttpPost without using nameValuePairs
  • Airflow dynamic tasks at runtime
  • How to connect Android Studio with SQL Server database
  • Wordpress PHP within PHP
  • visual studio (SSDT) 2017 unable to start debugging
  • How to add dynamic filter drop down using Jqgrid?
  • Get File Extension of File Dropped Onto Windows Form [closed]
  • set clipboard content in any browser
  • Alternative to __del__ for final result & killing processes in a class?
  • Eloquent Javascript: Can't understand how the number value is determined in the sum function
  • what is a good structure to save this data
  • Why is this Animatable property being set again?
  • bootstrappedUser - Jade or EJS to HTML
  • React / Webpack - “Module parse failed: Unexpected token - You may need an appropriate loader to han
  • Octave code for gradient descent using vectorization not updating cost function correctly
  • Can someone explain how Yii minimizing assets is supposed to work on Heroku?
  • Directed graph linear algorithm
  • Misplaced CAGradientLayer on iPhone 6s
  • Modifying native query cannot have named parameter bindings?
  • Adding native code to an existing Worklight hybrid app
  • Swift manually rotate view controller
  • How to use Flask's render_template from an ajax POST form submit
  • java.io.FileNotFoundException: Could not open ServletContext resource [/WEB-INF/SpringDispatcher-ser
  • How to use Streams api peek() function and make it work?
  • How to decleare char *const argv[] in swift [duplicate]
  • How to get rgb from transparent pixel in js
  • Firebase: How to read from external DB?
  • WPF custom control and direct content support
  • PHP Permalinks.. how to change?
  • media foundation H264 decoder not working properly
  • Running R's aov() mixed effects model from Python using rpy2
  • Access to a Matlab gui from the web
  • Create/delete users from text file using Bash script
  • Time Complexity of Fibonacci Algorithm [duplicate]
  • How to check if object is null in Java?