我有这段代码
export default function CheckHasSentGift(TransformedComponent) {
@connect(state=>state.global,{fetchGift})
class WithRedirect extends Component {
componentWillMount() {
this.props.fetchGift('sent')
}
render() {
this.props.sentGiftId &&
!this.props.location.pathname.includes('sent') &&
return <Redirect to={`/app/gift/${this.props.sentGiftId}/sent`} />
return <TransformedComponent { ...this.props } />
}
}
return WithRedirect
}
这是我的路线
<Route exact path='/app' component={CheckHasSentGift(App)} />
我没有问题进行重定向,它有效,但我在网络选项卡中看到了2次调用fetchGift api。然后我在渲染方法
中进行调试render() {
//this.props.sentGiftId &&
//!this.props.location.pathname.includes('sent') &&
//return <Redirect to={`/app/gift/${this.props.sentGiftId}/sent`} />
console.log('check render')
return <h1>test</h1>
//return <TransformedComponent { ...this.props } />
}
渲染只渲染一次,为什么在重定向后componentWillMount可以触发两次?
答案 0 :(得分:0)
实际上从React.v16.3开始不推荐使用componentWillMount
,并且最好使用componentDidMount来开始获取数据。
渲染只渲染一次,componentWillMount怎么可以 重定向后两次开火?
将您的console.log置于componentWillMount
,看看它是否被调用了两次。
还要确保第一个请求不是preflight request (OPTIONS method)哪个浏览器将触发来描述服务器之间的通信。您可以在浏览器开发人员工具中的“网络”选项卡中进行检查。