首页 > 解决方案 > 了解 reactjs 中的状态?

问题描述

我正在学习 Reactjs。我正在构建计数器应用程序。我认为下面的代码和反应中的状态是相同的。console.log 打印正确,但在 html 中它不会更改值。你能解释一下为什么代码不起作用吗?

import React, {useState} from "react";

let count = 0;
const Counter = (props) => {
    const setCount = ()=> {
        count = count + 1;
    };
    return (
        <div>
            <button onClick={()=> {
                setCount();
                console.log('counter: ', count);
            }}>button</button>
            <div>Hello {props.name} and your current number is: {count} </div>
        </div>
    )
};

export default Counter;

标签: javascriptreactjs

解决方案


更改变量不会重新呈现组件。

要查看 dom 中的更新,您必须重新渲染组件。有几种方法可以做到这一点。

  • 改变状态
  • 改变道具
  • 改变上下文

如果您将 count 变量置于一个状态并从那里触发它,您将看到它在组件中更新

文档中的示例

import React, { useState } from 'react';

function Example() {
  // Declare a new state variable, which we'll call "count"
  const [count, setCount] = useState(0);

  return (
    <div>
      <p>You clicked {count} times</p>
      <button onClick={() => setCount(count + 1)}>
        Click me
      </button>
    </div>
  );
}

推荐阅读