我的状态更改导致我的功能组件重新呈现。我注意到变量(let,var)有时会更新而有时却不会更新,这些变量显示在我的DOM上。是由状态触发的重新渲染时获取的变量的更新值。我可以使用状态来重新渲染触发器,然后只使用变量来进行更改,因为这消除了保持所有状态不变的开销吗?还是变量在挂载时保持其初始值?
例如,在Onclick事件中执行此操作-
let display;
const [state, setState] = useState();
...
OnClick () =>{
setState(newvalue);
display = newdisplay;
}
...
// In DOM
return (
<div>
{state}
{display}
</div>
)
答案 0 :(得分:0)
变量在状态更改之前已经更新,但是重新呈现页面仅显示您所做的更改,因此,如果未更新,则可能意味着您在更改变量之前已设置状态。
此外,请勿在渲染函数的返回值内设置状态,否则在涉及DOM更新时也可能会导致问题。
应做的事示例:
class MyComponent extends React.Component {
state = {
myStateVariable: "I'm in state"
};
myVariable = "Something cool"; // This variable is accessible from anywhere in your component using 'this'
updateVars = () => {
this.myVariable = "Something else thats cool";
this.setState({ myStateVariable: "I was now changed" });
}
render() {
let myLocalVariable = "Locally grown"; // This variable is only accessible within your render function
console.log(myLocalVariable);
myLocalVariable = "I was locally grown"; // Changing the variable
return (
<>
<p>{this.state.myStateVariable} is within state</p>
<p>{this.myVariable} will not update its self</p>
<p>{myLocalVariable} will always stay the same</p>
<button onClick={this.updateVars}>Click Me</button>
</>
);
}
}
感谢您发布问题,希望这可以为您解决问题。