javascript - 了解 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;
解决方案
更改变量不会重新呈现组件。
要查看 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>
);
}
推荐阅读
- ms-access - 如何根据其他数据的组合对数据进行平均?
- python - 无法使用从 keras 保存的模型将在线预测服务与图像输入一起使用
- python-3.x - 如何使用最小的modbus在python中实现slave?
- c - 使用 fscanf 从输入文件中逐行读取
- javascript - 验证和循环javascript
- installation - 如何正确安装 umbraco 7.10 或 8 卡在 db 配置上
- symfony - 如何从数据库中获取电子邮件参数
- python - 在 python 中解析 json 文件会产生困难
- python - 格式化字符串的所有行(即使 \n 在字符串中)
- ansible - 找到一个准确的字符串