Reactjs setState未更新状态
我正在从一个文件导出常量并将其导入另一个文件,如下所示: 常数.jsReactjs setState未更新状态,reactjs,Reactjs,我正在从一个文件导出常量并将其导入另一个文件,如下所示: 常数.js export const radio = { id: 0, name: 'station name', encodedName: 'stationName', url: 'http://www.some-station.io/', src: 'http://127.0.0.1:80/autodj', }; App.js import React, { Component } from 'react'; i
export const radio = {
id: 0,
name: 'station name',
encodedName: 'stationName',
url: 'http://www.some-station.io/',
src: 'http://127.0.0.1:80/autodj',
};
App.js
import React, { Component } from 'react';
import RadioService from './services/radio';
import { radio } from './constants';
class App extends Component {
constructor() {
super();
this.state = {
stream: {
np: undefined,
src: undefined,
playing: false
}
};
}
componentWillMount() {
this.startStream();
}
startStream = () => this.setState({ stream: { np: radio.name, src: radio.src } });
render() {
return (
<div>
<h4>Hello World...</h4>
</div>
);
}
}
export default App;
这将返回:
{stream: {…}}stream: {np: undefined, src: undefined, playing: false}
然而,我可以在构造函数中设置一些值,但是尝试设置进一步的状态是不适用的
例2:
class App extends Component {
constructor() {
super();
this.state = {
stream: {
np: radio.name,
src: radio.src,
playing: false
}
};
}
componentWillMount() {
this.startStream();
}
startStream = () => {
this.setState({ ...this.state, stream: { playing: true } });
this.exampleMethod();
};
setState是异步的,因此如果在之后立即使用console.log,则不会获得新状态
设置状态是一个异步函数。不能期望在setState语句之后立即更新状态 但是,您可以通过以下任一方式检查状态:
console.log(this.state)
setState
this.setState({…this.state,流:{playing:true}},()=>{
console.log(this.state);//应显示更新的状态
});
我相信
setState
函数是异步的。因此,您无法在调用该函数后立即获得新状态。尝试将控制台日志移动到render方法。尝试添加this.startStream=this.startStream.bind(this)代码>在构造函数中,这真的不会引发错误吗?因为它应该:“this”不在函数startStream的上下文中。您需要使用this.startStream=this.startStream.bind(this)在构造函数中绑定它;另一件事:您应该在构造函数中获取props并将其传递给super类,因此将其更改为constructor(props){super(props);…}。这将解决道具未更新的进一步问题。
class App extends Component {
constructor() {
super();
this.state = {
stream: {
np: radio.name,
src: radio.src,
playing: false
}
};
}
componentWillMount() {
this.startStream();
}
startStream = () => {
this.setState({ ...this.state, stream: { playing: true } });
this.exampleMethod();
};