gpt4 book ai didi

javascript - 如何像 redux 一样改变变量的值但使用react-hooks?

转载 作者:行者123 更新时间:2023-12-02 22:26:26 25 4
gpt4 key购买 nike

也许我的问题不匹配。如何使用另一个组件更改变量的值?我想使用react-hooks来改变值,就像redux一样。例如,我有变量 const [message, setMessage] = useState(''); ,位于 SearchScreen.js 文件中。我想在 Test.js 文件中更改此变量的值。

//SearchScreen file
import 'react-native-gesture-handler'
import React,{ useState } from 'react';
import {View, Text, Button} from 'react-native';
const SearchScreen = ({navigation}) =>{
const [message, setMessage] = useState('');
return(
<View>
<Text>{message}</Text>
<Button
title='enter to next bar'
onPress={() => navigation.navigate('Test')}
/>
</View>
);
};

export default SearchScreen;

和另一个文件

//Test file
import React,{useState} from 'react';
import {View, Text} from 'react-native';
const Test = () =>{
return(
<View>
<Text>
</Text>
</View>
);
};

export default Test;

我可以立即在Test.js文件中写入setMessage('Testing')

最佳答案

通过导航发送 setMessage 值消息的 CallBack

import React,{ useState } from 'react';
import {View, Text, Button} from 'react-native';
const SearchScreen = ({navigation}) =>{
const [message, setMessage] = useState('');
return(
<View>
<Text>{message}</Text>
<Button
title='enter to next bar'
onPress={() => navigation.navigate('Test',{setMessage})}
/>
</View>
);
};

export default SearchScreen;

之后从导航 Prop 中获取此回调,就像在测试 route 一样

测试文件

import React,{useState} from 'react';
import {View, Text} from 'react-native';
const Test = (props) =>{
const {navigation} = props;
const setMessage = navigation.state.params.setMessage;
return(
<View>
<Text>
</Text>
</View>
);
};

export default Test;

用于文档检查send value to other screen

关于javascript - 如何像 redux 一样改变变量的值但使用react-hooks?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59051969/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com