如何在react native中导出正在onPress函数中初始化的变量

hgb9j2n6  于 2022-11-25  发布在  React
关注(0)|答案(1)|浏览(114)

第一个
据我所知,Analysis页面似乎是在用户选择OnPress函数之前构建的。当按下OnPress函数时,Javascript不导出需要在Analysis中使用的变量num。如何在Analysis.js中使用num的更新值(在Journal.js中按下onPress函数后更新)?

5vf7fwbs

5vf7fwbs1#

听起来你应该把num存储在某个中央状态(如redux)或context
比如说

// contexts/mood.js
import { createContext, useState } from "react";

const MoodContext = createContext({ num: null, setNum: () => {} });

const MoodContextProvider = ({ children }) => {
  const [num, setNum] = useState();

  return (
    <MoodContext.Provider value={{ num, setNum }}>
      {children}
    </MoodContext.Provider>
  );
};

export { MoodContext, MoodContextProvider };

然后,您可以编写一个自定义钩子来使用此上下文并公开您的 analysis 功能。

// hooks/mood-analysis.js
import { useContext } from "react";
import { MoodContext } from "../contexts/mood";

const useMoodAnalysis = () => {
  const { setNum } = useContext(MoodContext);

  return async (inputValue) => {
    // ...
    setNum(2);
  };
};

剩下的就是在提供程序中 Package 组件...

<MoodContextProvider>
  <Routes>
    {/* ... just an example ... */}
  </Routes>
</MoodContextProvider>

使用Journal组件中的挂钩...

const analyse = useMoodAnalysis();

const onPress = async () => {
  // ...
  await analyse(someInputValue);
};

并读取Analysis组件中的上下文值

const { num } = useContext(MoodContext);

相关问题