如何在 React 中扩展另一个组件的组件中使用 setState 函数更改状态
How can I change the status with setState function in a component that extends another in React
当我在 MyComponent 中使用 steState 函数时,它什么都不做,并且在控制台中记录原始状态?
这是我的BaseComponent代码:
export class BaseComponent extends React.Component {
constructor (props) {
super(props);
this.state = {
foo: 'bar'
}
this.setMyState();
}
render() { return (<div></div>); }
}
这是扩展组件代码:
import { BaseComponent } from 'path/to/BaseComponent';
export class MyComponent extends BaseComponent {
setMyState () {
console.warn('MyComponent --->', this.state); // Return {foo: bar}
this.setState({ foo: 'koala' });
console.warn('MyComponent --->', this.state); // Return {foo: bar}
}
}
我怎样才能让它发挥作用?
我认为你遇到的问题不是因为 setMyState()
没有正确修改你的状态,而是因为 react this.setState()
函数实际上是异步的,所以新的状态值是'保证在您 console.warn()
时设置在下一行。
See this link for a more detailed explanation about the async nature of this.setState()
这是 React 文档的摘录,对其进行了解释。
Think of setState() as a request rather than an immediate command to
update the component. For better perceived performance, React may
delay it, and then update several components in a single pass. React
does not guarantee that the state changes are applied immediately.
当我在 MyComponent 中使用 steState 函数时,它什么都不做,并且在控制台中记录原始状态?
这是我的BaseComponent代码:
export class BaseComponent extends React.Component {
constructor (props) {
super(props);
this.state = {
foo: 'bar'
}
this.setMyState();
}
render() { return (<div></div>); }
}
这是扩展组件代码:
import { BaseComponent } from 'path/to/BaseComponent';
export class MyComponent extends BaseComponent {
setMyState () {
console.warn('MyComponent --->', this.state); // Return {foo: bar}
this.setState({ foo: 'koala' });
console.warn('MyComponent --->', this.state); // Return {foo: bar}
}
}
我怎样才能让它发挥作用?
我认为你遇到的问题不是因为 setMyState()
没有正确修改你的状态,而是因为 react this.setState()
函数实际上是异步的,所以新的状态值是'保证在您 console.warn()
时设置在下一行。
See this link for a more detailed explanation about the async nature of this.setState()
这是 React 文档的摘录,对其进行了解释。
Think of setState() as a request rather than an immediate command to update the component. For better perceived performance, React may delay it, and then update several components in a single pass. React does not guarantee that the state changes are applied immediately.