目前情况
一个表单Component一个列表Component动作
表单送出资料后,跳转到列表,跳转到列表后,会更新已送出资料
说明
这动作其实很常见,但是在SPA里面作法就要转一下
表单跳转:会回传state
告诉表单要重新撩取资料
<Redirect to={{ pathname: '/product/table', state: { reload:true} }} />
列表捞取资料的function:
getProduct() { axios.get(`http://localhost/product`).then(response => { this.setState({ product: response.data }) }) }
但问题是跳转到列表Component时这个state.reload
只会在render
中出现
我在列表得constructor
跟render
都有console.log
,但最后只有在render里面才有出现资料
那这样就有问题了?
假设我要抓取<Redirect>
传来的state.reload
去判断是否要更新,就必须把getProduct
放到render
执行
但是this.setState
是不能在render 执行的
getProduct() { axios.get(`http://localhost/product`).then(response => { this.setState({ product: response.data }) }) }
那这时候揪竟该如何解决呢?
解法
componentWillReceiveProps(nextProps) {if (nextProps.location.state !== undefined && nextProps.location.state.reload === true) {axios.get(`${APIURL.localhost}/product`).then(response => {this.setState({ product: response.data })})}}