React Native:使用上下文将子状态与父状态挂钩



我正在尝试在ChildScreen中重新渲染{userNumbers}。我设法在主页中添加userNumbers状态,但它不会重新呈现文本。

用户上下文.js

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

首页.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>
)
}

儿童屏幕.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>
)
}

您需要在更改state.users时重新创建userContext value,方法是将state.users添加为依赖项以使用 Memo,否则上下文值将继续保存相同的值引用,并将注意任何侦听器的触发器更改

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

此外,您应该将化简器定义为纯化,即它不应该使用闭包状态

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

附言您无需定义要asyncaddUsers函数。dispatch异步发生,但需要重新渲染才能生效,您无需等待它

您需要重新评估useContextstate.users更改:

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

相关内容

  • 没有找到相关文章

最新更新