【发布时间】:2018-05-02 09:46:07
【问题描述】:
问题是组件被渲染了两次,一次是初始状态,一次是在 axios promise 中的 setState 方法之后。为什么会发生这种情况,我该如何解决。
我同时使用了 componentWillMount 和 componentDidMount。我作为菜鸟,努力尝试,但未能弄清楚原因。
export default class Dashboard extends Component{
constructor(props) {
super(props)
this.state = {
data: {
okay: 'lul'
}
}
}
componentWillMount() {
axios
.get('/api/data?param1='+this.props.location.state.param1+'¶m2='+this.props.location.state.param2)
.then(res => {
if (res.status != 401) {
if(res.err)
console.log('Error while retrieving: ', res.err)
else {
this.setState({
data: res.data.data
})
}
} else {
console.log('Unauthorized!');
}
})
}
render() {
return (
<Segment inverted vertical>
<CardContainer data={this.state.data}/>
</Segment>
)
}
}
即使是与 React / JS / 通用编程相关的基本建议也非常感谢
【问题讨论】:
-
你为什么认为这是个问题?如果您不想在获取数据之前显示任何内容,您可以在 render 方法中检查
this.state.data,如果还没有数据可以显示,则返回null。setState将导致每次调用render方法。 -
@HåkenLid 您提出的解决方案非常有效。但是我怎样才能用正确的数据只渲染一次组件呢?我是不是必须在构造函数里面写 axios 请求,然后设置初始状态?
-
这种行为是 react 应该如何工作的。这不是一个错误。调用
render真的很便宜,因为 react 会以有效的方式更新 dom。在某些情况下,您可能希望在重新渲染发生时进行调整。这在此处的反应文档中进行了讨论:shouldComponentUpdate In Action
标签: reactjs