我正在尝试通过在一个屏幕上输入用户名并将其显示在密码屏幕上来学习Context API。我的问题是如何显示该用户名。我尝试的方式没有任何显示。我知道这与包装组件时传递值的方式有关。
Signup.js(主要组件)
import Username from './Username';
import Password from './Password'
import { SignUpContext } from './context';
const Stack = createStackNavigator();
const Signup = () => {
const signUpDetails = {
username: null,
password: null,
}
const signUpReducer = (prevState, action) => {
switch (action.type) {
case 'USERNAME':
return {
...prevState,
username: action.username,
};
case "PASSWORD":
return {
...prevState,
password: action.password,
};
}
}
const [signupState, dispatch] = React.useReducer(signUpReducer, signUpDetails)
const signupContext = React.useMemo(() => ({
sendUsername: (username) => {
dispatch({ type: "USERNAME", username });
},
}))
return (
<SignUpContext.Provider value={signupContext}>
<Stack.Navigator>
<Stack.Screen name='Username' component={Username} options={{ headerShown: false }} />
<Stack.Screen name='Password' component={Password} options={{ headerShown: false }} />
</Stack.Navigator>
</SignUpContext.Provider>
)
}
export default Signup;
Username.js
import { SignUpContext } from './context';
const Username = ({ navigation }) => {
const [data, setData] = React.useState({
username: '',
})
const { sendUsername } = React.useContext( SignUpContext );
const textInputChange = (val) => {
setData({
...data,
username: val,
})
}
const handleNextButton = (username) => {
sendUsername(username)
navigation.navigate('Password');
}
return (
<View>
<TextInput placeholder='Username'
onChangeText={(val) => textInputChange(val) }></TextInput>
<Button title='Next' onPress={() => { handleNextButton(data.username) }} />
</View>
)
}
export default Username;
Password.js(消费者)
import { SignUpContext } from './context';
const Password = ({ navigation }) => {
return (
<SignUpContext.Consumer>
{context => (
<View>
<Text>{context.username}</Text> {/* somehow display username */}
<TextInput placeholder='Password'></TextInput>
<Button title='Submit'></Button>
</View>
)}
</SignUpContext.Consumer>
)
}
export default Password;
问题是在传递状态以及我在值中的操作时。因此,在signupState
中添加我的signupContext
即可解决。
所以,在Signup.js中:
const signupContext = React.useMemo(() => ({
signupState, // adding the signup state here.
sendUsername: (username) => {
dispatch({ type: "USERNAME", username });
},
}))
并且在Password.js(消费者)中,可以通过以下方式检索数据(用户名):
const Password = ({ navigation }) => {
const context = useContext(SignUpContext);
console.log("context is ", context.signupState.username); // Fetching username here.
const username = context.signupState.username;
return (
<View>
<Text>{username}</Text>
<TextInput placeholder='Password'></TextInput>
<Button title='Submit'></Button>
</View>
)
}