简体   繁体   中英

How to re-render after state is changed in react js?

import React from 'react'

export default function App(){
    const[flag,setFlag] =React.useState({1:false,2:false})

    const change=(id)=>{
        flag[id] = !flag[id]
        setFlag(flag)
        console.log(flag)
    }

    return(
        <div>
            {flag[1] ? <p>this is true</p> : <p>this is false</p>}
            <button onClick={()=>change(1)}>Change</button>
        </div>
    )
}

I want to change my output based on flag state. While flag JSON is changing, but it's not re-rendering.

your code is working fine.

const change=(id)=>{
   console.log(flag[id]);
        flag[id] = !flag[id]
        setFlag(flag)
        console.log(flag)
    }

Could you check the render method.

Check here https://codepen.io/palash924332931/pen/VwYpwOq?editors=1111

You should be using setFlag() to change the state instead of changing flag directly. By using the setter for the flag state, you can call render() if you use setFlag() . In order to use setFlag() with your current setup, you can use computed property names like so:

const change = id => {
  setFlag(currentFlag => ({[id]: !currentFlag}));
}

The state updater returned by useState will not rerender the component's children if you set a new value that equals the current value. https://reactjs.org/docs/hooks-reference.html#bailing-out-of-a-state-update

    function App() {
  const [flag, setFlag] = React.useState({ 1: false, 2: false });

  const change = id => {
    var newFlag = Object.assign({}, flag);
    newFlag[id] = !flag[id];
    setFlag(newFlag);
  };
  return (
    <div>
      {flag[1] ? (
        <p>this is true</p>
      ) : (
        <p>this is false</p>
      )}
      <button onClick={() => change(1)}>Change</button>
    </div>
  );
}

codepen example

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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