0

我在 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)
};
4

1 回答 1

0

看起来你的getPrivateKey函数是一个 thunk,但你没有调度它?没有什么能阻止你从 thunk 返回值。

const getPrivateKey = async (dispatch) => {
  const privKey = await fetchKeyFromServer();
  dispatch({
   type: 'UPDATE',
   value: privKey 
  });
  return privKey // return the key here to whoever wants to use the value immediately.
};

然后在您useEffect的组件中,您可以轻松使用返回值:)

useEffect(() => {
    const configure = async () => {
      //make sure you 'dispatch' this thunk
      const key = await dispatch(getPrivateKey());

      // pass the key
      await dispatch(connectWithKey(key));
      ...
    };
    ....
  }, []);

上面的代码假设 theconnectWithKey也是一个 thunk。如果是这样,您可以设计 thunk 以使其使用传递的值或从 redux 存储中读取它。

const connectWithkey = (privateKey: passedPrivateKey) = async (dispatch, getState) => {
  const state = getState();
  let privateKey = state.whatever.the.path.is.to.privateKey;

  // use the passed private key if it is present.
  if (passedPrivateKey) {
    privateKey = passedPrivateKey;
  }

  await connectToServer(privateKey)
};

我在我的应用程序中多次使用过这种方法。这样您就不需要依赖选择器中的状态。如果您选择依赖该状态,您的依赖项useEffect应该相应更新。现在它是一个空数组,这就是为什么效果不会在任何状态更改时再次运行(它就像componentDidMount生命周期函数一样)。

const privateKey = useSelector(({ main }) => main.privateKey);

useEffect(() => {
 await getPrivateKey();

 if (privateKey) {
   await connectWithKey();
 }
}, [privateKey]);

这样,每次privateKey状态更改时,您的钩子都会重新运行。不过,您可能需要为您的 thunk 设置某种条件connectWithKey,以便在密钥为空时它不会运行。

于 2020-02-22T20:42:32.080 回答