关于网友提出的“ 数据变了,子组件数据不更新,还是第一次渲染时传的数据”问题疑问,本网通过在网上对“ 数据变了,子组件数据不更新,还是第一次渲染时传的数据”有关的相关答案进行了整理,供用户进行参考,详细问题解答如下:
问题: 数据变了,子组件数据不更新,还是第一次渲染时传的数据描述:
ExerciseDetail是提示框点开后的详情页。
我用react-keeper做路由,跳转时传路由地址和数据就可以了:Control.go(/exercise/1, state);
点提示框跳转/exercise/1之后,页面渲染ok,这个时候再来一个提示框,从1跳转/exercise/2
我发现urllimit在组件直接用可以更新渲染,但是给子组件就不传更新后的数据
import React from "react";
import { createSelector } from 'reselect';
import { connect } from 'react-redux';
import { actions } from '../Root/redux'
import { Control, Link } from 'react-keeper'
class ExerciseDetail extends React.Component {
constructor(props) {
super(props);
this.exercise = Control.state.exercise;
this.state = {
}
}
componentWillReceiveProps(nextProps) {
if (!Control.state) {
return;
}
this.setState({
options: this.exercise.options,
problemid: this.exercise.problemid,
})
this.exercise = Control.state.exercise;
console.log(Control.state);//可以收到每次发的数据
}
render() {
const exercise = this.exercise;
const url = exercise.url;
const limit = exercise.limit;//输出这里数据是最新的,但是不给Options传更新的数据
return
{url}
{limit}
//都可以及时更新渲染
}
}
//子组件
function Options(props) {
const limit = props.limit;
//子组件里输出一直是第一次渲染传的数据,第二次就没触发传值
const url = props.url;
}
return
解决方案1:
先把componentWillReceiveProps
的生命周期搞清楚。componentWillReceiveProps
方法中,要通过nextProps
来改变state
.你setState
的那个值,与nextProps
毛关系都没有,当然子组件不更新了。
另外,props
也可以render
,所以不需要componentWillReceiveProps
,直接在render
中,根据props
实现就好了。