【问题标题】:problem call `useContext` then my other `state` set to default value问题调用`useContext`然后我的其他`state`设置为默认值
【发布时间】:2021-11-16 12:06:09
【问题描述】:

在我的代码中,我使用了一个 context 来保存数据和一个 state 来获取活动 ID。我的问题是当我setState 然后setContext 时,当我得到state 值时,我看到state 设置默认值!


export default function AddKnowledgeScreen({ route, navigation }) {

  const { TmpKnowledge, SetTmpKnowledge } = useContext(addKnowledgeContext);

   const [activeKnowlegeId, SetactiveKnowlegeId] = useState(-1);

  const myref = useRef(null);

return(
     <View style={{ flex: 1, alignItems: 'center', backgroundColor: Color.Background, }}>
          <Button
                onPress={() => {
                         SetactiveKnowlegeId(5);
                         var knowledgeData = { Id: 5, Name: "jack" };
                         SetTmpKnowledge(knowledgeData);
                        }>
          </Button>
     </View>
);
}

我发现当我设置我的context 屏幕重新渲染并且所有state 设置为默认值!

【问题讨论】:

    标签: react-native react-hooks use-state use-context createcontext


    【解决方案1】:

    不确定我是否正确地回答了您的问题,但我了解您正在尝试设置本地状态并立即使用此新值在您的上下文中设置您的值

    如果是这样,这将是因为 useState 钩子是异步的,因此在设置上下文值时您仍然会获得默认值

    这里有一些更详细解释的链接:

    Why is setState in reactjs Async instead of Sync?

    Is useState synchronous?

    【讨论】:

    • 我在设置上下文时发现,页面重新渲染和所有状态都变为默认值。我不想那样!!
    猜你喜欢
    • 2013-03-01
    • 2018-12-04
    • 1970-01-01
    • 1970-01-01
    • 2013-03-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-12-28
    相关资源
    最近更新 更多