[英]can i declare a global variable outside the class in reactjs
var array= []
class Body extends Component {
state= {
input: '',
oprStatus: false,
check: false,
count: 0,
oprArray: null
} }
now as i know that i cant update the 'oprArray' array inside the state by using push so what i was thinking that what if i declare a variable outside the class and update that array and then update the 'oprArray' inside state现在我知道我无法使用 push 更新状态内的“oprArray”数组,所以我在想如果我在类外声明一个变量并更新该数组然后更新状态内的“oprArray”会怎样
array.push(2);
this.setState({
oprArray: array
)}
That doesn't solve the problem, because you'd still be mutating state rather than setting new state.这并不能解决问题,因为您仍然会改变状态而不是设置新状态。 Once you've set
oprArray: array
in your state the first time, the state and the global array
variable are both pointing to the same array.第一次在状态中设置
oprArray: array
后,状态和全局array
变量都指向同一个数组。 The next time, that push
is modifying state directly — which is a no-no with React state.下一次,
push
是直接修改状态——这是 React 状态的禁忌。
To add a new item into your oprArray
, you do it like this:要将新项目添加到您的
oprArray
,您可以这样做:
this.setState(({oprArray}) => ({oprArray: [...oprArray, 2]}));
That:那:
Uses the callback form of setState
, which is necessary when you're modifying state (a new oprArray
with the new entry, 2
) based on existing state (the previous contents of oprArray
).使用
setState
的回调形式,当您根据现有状态( oprArray
的先前内容)修改状态(带有新条目2
的新oprArray
时,这是必需的。
Creates a new array with the additional item, via spread notation.通过扩展符号创建一个带有附加项的新数组。
Live Example:现场示例:
const {Component} = React; class Body extends Component { state = { input: '', oprStatus: false, check: false, count: 0, oprArray: null }; componentDidMount() { // Since your state starts with `null`, I assume you receive initial data // via ajax or similar; emulated here with a timeout setTimeout(() => { this.setState({oprArray: [0, 1]}); // Initial data isn't based on existing state // Now set up getting more data later setTimeout(() => { // Additional data this.setState(({oprArray}) => ({oprArray: [...oprArray, 2]})); }, 800); }, 800); } render() { const {oprArray} = this.state; return ( <div>oprArray: {oprArray ? oprArray.join(", ") : "(none)"}</div> ); } } ReactDOM.render(<Body />, document.getElementById("root"));
<div id="root"></div> <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>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.