Props归结为子组件,它不会触发任何东西。
父组合和子组件都有代码。
我在父类中使用了componentDidMount(){}
。
并在render子组件中设置props。在子类中,我使用了componentWillReceiveProps(){}
。但是在孩子this.setState(){}
中并没有改变状态。
伙计们帮助我。我可以弄清楚它为什么不起作用。
父:
class Recipes extends React.Component{
constructor(props){
super(props);
this.state = {
recipes: [],
Loaded: false
};
this.getRec = this.getRec.bind(this);
this.views = this.views.bind(this);
}
shouldComponentUpdate(nextProps, nextState){
console.log(nextState);
if (nextState.Loaded !== this.state.Loaded || nextProps !== this.props){
return true;
}
}
componentDidUpdate(){
}
componentWillMount(){
this.views();
}
componentDidMount(){
this.getRec();
}
componentWillUnmount(){
}
componentWillUpdate(){
}
getRec(_){
fetch('http://localhost:5000/recipes')
.then(response => response.json())
.then(data => {
this.setState({recipes: data, Loaded: true});
})
.then(data => this.render())
.catch(err => console.log(err))
}
views(){
const {recipes} = this.state;
const howManyRecipes = recipes.length;
const view = howManyRecipes > 0 ? 'hi' : <Route component={CreateProposal}/>
}
render() {
const {recipes} = this.state;
const howManyRecipes = recipes.length;
console.log(howManyRecipes);
return (
<div>
<div>Our community did {howManyRecipes} recipes</div>
<RecipeList recipeList={this.state.recipes} Loaded={this.state.Loaded}/>
</div>
)
}
}
子:
class RecipeList extends Component{
constructor(props){
super(props);
this.state = {
recipes: this.props.recipeList,
loaded: this.props.Loaded
}
console.log(this.state.loaded);
this.renderRec = this.renderRec.bind(this);
}
componentWillReceiveProps(nextProps){
var answ = nextProps !== this.props;
this.setState((prevState) => {return (prevState.recipes: nextProps.recipeList.data)});
console.log(this.state, nextProps.recipeList.data, answ);
return answ;
}
// shouldComponentUpdate(nextProps, nextState){
// var answ = nextState.loaded !== this.state.loaded;
// console.log("should component update? " + answ);
// return answ;
// }
renderRec(recipe){
return <div key={recipe.id}>{recipe.name}</div>
}
render(){
return(
<div>
<div>{this.state.recipes.length}</div>
{this.state.recipes.map(this.renderRec)}
</div>
);
}
}