【发布时间】:2021-11-10 14:04:03
【问题描述】:
我正在类组件中处理 React Js 我正在声明一些状态,然后从 API 获取数据并将该状态更改为新值,但 React 并未呈现该新状态值。但是如果我在 console.log() 中声明它会在控制台上给我新的价值。
我的代码
class Home extends Component {
constructor(props) {
super(props);
this.state = {
unread: 0,
}
this.getUnread()
}
getUnread = async () => {
let data = await Chatapi.get(`count/${this.props.auth.user.id}/`).then(({ data }) => data);
this.setState({ unread: data.count });
console.log(this.state.unread)
}
render() {
const { auth } = this.props;
return (
<div>
{this.state.unread}
</div>
)
}
这是在控制台上打印 2 但在屏幕上呈现 0。如何获取更新后的状态 (2) 以在屏幕上呈现。
如果我访问另一个页面然后返回此页面,那么它正在呈现新的状态值 (2)。
【问题讨论】:
标签: reactjs