Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
208 views
in Technique[技术] by (71.8m points)

reactjs - state rendering in react.js

I have a very simple question which has been bugging me. I am relatively new to react and having issues with state. If I have a component that creates a state variable like below

const [state, setState] = useState(null)

and let in the code I do something like this...

setState(50)

Changing the state forces a re-render which in turn re-initializes the state variable as null. What am I doing wrong? I want the app the re-render when state changes and leave state as 50 in this example but when it re-renders it re-initializes the state as null. Super strange.

actual code...

const ConnectBackend = props => {
    const [moisture, setMoisture] = useState(null)

    let temp = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
    var i = 0;
    function myLoop() {
        setTimeout(function() {
            setMoisture(temp[i]);
            console.log(moisture)
            i++;
            if (i < 10) {
                myLoop();
            }
        }, 3000)
    }
  
    myLoop(); 
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Where are you using the setState? If you do it like so, it shouldn't be an issue.

const App = () => {
  const [state, setState] = React.useState(null)
  
  React.useEffect(() => {
    setState(50);
  }, []);
  
  return <p>{state}</p>
}

ReactDOM.render(<App />, document.getElementById("root"));
<script src="https://unpkg.com/react@17/umd/react.production.min.js" crossorigin></script>
<script src="https://unpkg.com/react-dom@17/umd/react-dom.production.min.js" crossorigin></script>
<div id="root"></div>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...