问题在于组件被渲染了两次,一次是使用初始状态,另一次是在 axios promise 的 setState 方法之后再次渲染。为什么会出现这种情况,我该如何解决这个问题。
我已经尝试使用 componentWillMount 和 componentDidMount 两种方法,但由于自己的菜鸟水平,未能成功找到原因。
我已经尝试使用 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/通用编程有关的基本建议。
this.state.data
并且如果还没有数据要显示就返回null
。每次调用setState
都会导致render
方法被调用。 - Håken Lidrender
方法的成本相当低,因为 React 会以高效的方式更新 DOM。在某些情况下,您可能希望调整重新渲染发生的时间。React 文档中讨论了这个问题: [shouldComponentUpdate In Action] (https://reactjs.org/docs/optimizing-performance.html#shouldcomponentupdate-in-action)。 - Håken Lid