与一起
componentDidMount,您还需要在页面中实现
componentWillReceiveProps或使用
getDerivedStateFromProps(从v16.3.0起),
Products因为同一组件已
re-rendered更新,
params并且
notre-mounted当您更改路线参数时,这是因为参数是作为prop传递给组件的,而onprops会发生变化,React组件会重新渲染而不是重新安装。
编辑:
从v16.3.0起,用于
getDerivedStateFromProps根据道具设置/更新状态(无需在两种不同的生命周期方法中指定它)
static getDerivedStateFromProps(nextProps, prevState) { if (nextProps.match.params.product !== prevState.currentProductId){ const currentProductId = nextProps.match.params.product const result = productlist.products.filter(obj => { return obj.id === currentProductId; }) return { product: result[0], currentId: currentProductId, result } } return null;}在v16.3.0之前的版本中,您将使用componentWillReceiveProps
componentWillReceiveProps(nextProps) { if (nextProps.match.params.product !== this.props.match.params.product) { const currentProductId = nextProps.match.params.product const result = productlist.products.filter(obj => { return obj.id === currentProductId; }) this.setState({ product: result[0], currentId: currentProductId, result }) } }


