【发布时间】:2018-04-08 16:25:37
【问题描述】:
我正在从一个文件中导出 const 并将其导入到另一个文件中,如下所示:
constants.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';
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;
我希望我的初始状态与构造函数中设置的一样,然后在 componentWillMount 上,我想使用常量文件中的值设置状态,然后围绕组件和流添加更多逻辑。
但是我发现,我的状态没有被更新,如果我在调用 setState 后控制台日志,状态仍然是未定义的,如果我引入了一个需要状态值的方法,稍后在执行堆栈中,它是未设置。
示例:
startStream = () => {
this.setState({ stream: { np: radio.name, src: radio.src } });
this.exampleMethod();
};
exampleMethod = () => console.log(this.state);
这会返回:
{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函数是异步的。因此,您无法在调用该函数后立即获得新状态。尝试将控制台日志移动到渲染方法。 -
尝试在构造函数中添加
this.startStream = this.startStream.bind(this); -
这真的不会给您带来错误吗?因为它应该:“this”不在函数 startStream 的上下文中。您需要使用 this.startStream = this.startStream.bind(this); 在构造函数中绑定它另一件事:您应该将构造函数中的道具传递给超类,因此将其更改为 constructor(props) { super(props); ... }。这将解决道具未更新的进一步问题。
标签: reactjs