我在 React-Native 项目中有一个屏幕,它基本上只是在从服务器获取数据的同时呈现加载图标,然后将用户带到主屏幕。第一个函数getPrivateKey()将返回私钥并使用 redux 将其存储在 state 中,然后下一个函数connectWithKey()将使用该密钥进行连接。
我面临的问题是,在connectWithkey()运行时,它使用的是私钥的初始空值,而不是更新后的值。这是代码,如果我很愚蠢,很抱歉,这是漫长的一天:(
export default DataLoader = props => {
//private key - this should, in theory, update after getPrivateKey()
const privateKey = useSelector(({ main }) => main.privateKey);
const dispatch = useDispatch();
useEffect(() => {
const configure = async () => {
//this will update the private key
await getPrivateKey();
//this should use the new private key from useSelector, but instead is using the initialised empty object
await connectWithKey();
props.navigation.navigate('MainScreen');
};
configure();
}, []);
//.... more code below....
我尝试将 privateKey 添加到刚刚导致无限循环的数组依赖项中,并且我检查了 redux 存储中的值是否已更新 - 所以我有点迷路了!从本质上讲,useSelector 钩子似乎没有获得新的价值。任何帮助将不胜感激谢谢!
编辑 - 根据要求添加更多代码
const getPrivateKey = async () => {
const privKey = await fetchKeyFromServer();
dispatch({
type: 'UPDATE',
value: privKey
});
};
const connectWithkey = async () => {
//the privateKey here should be the updated value from useSelector
await connectToServer(privateKey)
};