简体   繁体   English

不要渲染新屏幕 usecontext usestate react object boolean simple

[英]dont render new screen usecontext usestate react object boolean simple

im using useState to store an object, with one property boolean, and using ternary operator to get the switch between screens.我使用 useState 来存储一个对象,具有一个布尔属性,并使用三元运算符来获取屏幕之间的切换。

when i click the button, i see in the console that the value is changed but the screen doesn't update, doesnt show "i'm in", the console show this:当我单击按钮时,我在控制台中看到值已更改但屏幕没有更新,没有显示“我在”,控制台显示:

{logged: false, name: 'example'} Login.js:7
{logged: true, name: 'example'} Login.js:9

When i change the useState to a single variable, not an object, works (changing the childrens), but ai really want to use with an object.当我将 useState 更改为单个变量而不是对象时,会起作用(更改孩子的),但我真的想与对象一起使用。 So i want to know why isn't working, is some property of useContext?所以我想知道为什么不起作用,是 useContext 的某些属性吗? or limitation on useState?或对 useState 的限制? meanwhile i will use useState with a single asignation (boolean) an multiple variables-lines同时我将使用带有单个指定(布尔值)和多个变量行的 useState

The reason to use useContext is for pass down the variables, in case of many layers of childrens使用 useContext 的原因是为了传递变量,以防多层子

App.js应用程序.js

    import React, { useState } from "react"
    import AppMain from './Components/AppMain';
    import Login from './Components/Login';
    import ExampleContext from "./ExampleContext";

    function App() {
      const [user, setuser] = useState({"logged" : false, name: "example"})
      return (
        <ExampleContext.Provider value={{ user, setuser }}>
            {user.logged? <AppMain />:<Login />}
          </ExampleContext.Provider>
      );
    }

    export default App;

AppMain.js AppMain.js

    import React from "react"

    function AppMain() {
      return (
        <>
          <p>I'm in</p>
        </>
      )
    }

    export default AppMain

Login.js登录.js

    import React, { useContext } from "react"
    import ExampleContext from "../ExampleContext"

    function Login() {
      const {user,setuser} = useContext(ExampleContext)
      function log(){
        console.log(user)
        setuser(a=> {a.logged = true; return a})
        console.log(user)
      }
      return (
        <>
          <button onClick={log} >Log in</button>
        </>
      )
    }

    export default Login

ExampleContext.js示例上下文.js

    import { createContext } from "react"

    const ExampleContext = createContext()

    export default ExampleContext

Nothing is wrong with useState or useContext, your way of mutating state is wrong. useState 或 useContext 没有错,你改变状态的方式是错误的。 set it this way:这样设置:

setuser(a=>({...a,logged:true}));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM