简体   繁体   English

reactjs中状态改变后如何重新渲染?

[英]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.虽然标志 JSON 正在改变,但它不会重新呈现。

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在这里查看https://codepen.io/palash924332931/pen/VwYpwOq?editors=1111

You should be using setFlag() to change the state instead of changing flag directly.您应该使用setFlag()来更改状态而不是直接更改flag By using the setter for the flag state, you can call render() if you use setFlag() .通过对flag状态使用 setter,如果使用setFlag() ,则可以调用render() setFlag() In order to use setFlag() with your current setup, you can use computed property names like so:为了在当前设置中使用setFlag() ,您可以使用计算属性名称,如下所示:

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.如果您设置的新值等于当前值,则 useState 返回的状态更新程序将不会重新渲染组件的子组件。 https://reactjs.org/docs/hooks-reference.html#bailing-out-of-a-state-update https://reactjs.org/docs/hooks-reference.html#baiiling-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 代码笔示例

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

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