让我们直接使用代码来演示:
function App() {
let message = '!!message init value, this should not be displayed!!';
const busyState = React.useState(true);
let isBusy = busyState[0];
let setIsBusy = busyState[1];
React.useEffect(() => {
log('didMount');
getLatestMessage();
}, []);
function log(message) {
document.getElementById('console').innerText = message;
}
function getLatestMessage() {
log('getting latest message...');
setTimeout(() => {
log('http call complete, there was a message for you');
message = 'Hello World'
setIsBusy(false);
}, 3000);
}
return (
<div>
{
isBusy ?
<h4>
Busy Getting Data
</h4> :
<h4>
{message}
</h4>
}
</div>
);
}
ReactDOM.render(<App />, document.getElementById('root'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.10.2/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.10.2/umd/react-dom.production.min.js"></script>
<div id="root"></div>
<label>Console:</label>
<h4 id="console" style="color: red">
</h4>
我在这里使用状态。我正在使用 isBusy 状态变量来导致我的组件的另一次渲染。但 message
仍保留其初始化值。我知道我也可以使用消息变量的 useState 钩子(Hook)来解决这个问题,但我认为 isBusy 状态标志足以“刷新”旧的 ReactJS 功能组件 UI...? p>
最佳答案
每次触发重新渲染时,都会调用您的功能组件(它只是一个函数)。变量“message”的值在函数定义顶行的每个渲染中设置为其“初始值”。所以值(value)永远不会改变。要在多个渲染周期期间保留状态,您需要使用状态。
关于javascript - 为什么在以下场景中 AJAX 之后需要使用 ReactJS 状态来更新 UI,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58864622/