[恸] [react-router-dom] <Redirect /> 跳转只会re-render Comp

目前情况

一个表单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中出现
我在列表得constructorrender都有console.log,但最后只有在render里面才有出现资料

http://img2.58codes.com/2024/20103556jptCXjT3Gx.png

那这样就有问题了?
假设我要抓取<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 })})}}

关于作者: 网站小编

码农网专注IT技术教程资源分享平台,学习资源下载网站,58码农网包含计算机技术、网站程序源码下载、编程技术论坛、互联网资源下载等产品服务,提供原创、优质、完整内容的专业码农交流分享平台。

热门文章