gpt4 book ai didi

javascript - 如何在 react.js 中将数据从父级传递给子级

转载 作者:数据小太阳 更新时间:2023-10-29 05:11:32 26 4
gpt4 key购买 nike

我有一个父组件,它有 1 个子组件。我通过 Prop 传递数据来更新我的 child 。最初,它工作正常,但是当我单击一个按钮并使用 setState 更新状态时,在 setState 完成时, child 将使用旧值呈现。我已经在 child 中使用 componentWillReceiveProps 解决了这个问题,但这是正确的方法吗?

在下面的代码中,如果我在 filterResults 函数中执行 setState,它不会更新 Emplist 组件。

import React, { Component } from 'react';
import {Search} from './search-bar'
import Emplist from './emplist'

class App extends Component {
constructor(props){
super(props);
this.emp=[{
name:'pawan',
age:12
},
{
name:'manish',
age : 11
}]
this.state={emp:this.emp};
this.filterResults=this.filterResults.bind(this);
}

filterResults(val)
{
if(this.state)
{
let filt=[];
filt.push(
this.emp.find(e=>{
return e.age==val
})
);
this.setState({emp:filt});
}
}

render() {
return (
<div className="App">
<Search filterResults={this.filterResults}/>
<Emplist emp={this.state.emp}/>
</div>
);
}
}
export default App;

EmpList Componet

import React,{Component} from 'react'

export default class Emp extends Component
{
constructor(props){
super(props);

this.emplist=this.props.emp.map(e=>{return <li>{e.name}</li>});
this.next=this.emplist;
}

componentWillReceiveProps(nextProps,nextState,prevProps,prevState,nextContext,prevContext){
// this.props.updated(this.props.empo);
this.next=nextProps.emp[0];
if(this.next)
this.emplist= nextProps.emp.map(e=>{return <li>{e.name}</li>});
}

render(){
if(!this.next)
return <div>name not found</div>
else
return (
<div>
<br/>
<p>The list is here</p>
<ul>
{this.emplist}
</ul>
</div>
)
}
}

最佳答案

如果你想从父级传递给子级,你可以使用 props 传递,如果你想做相反的事情,你可以将一个函数从父级传递给子级,然后使用这个传递的函数将一些东西发送回父级。

child 看起来像这样

class Reciepe extends Component{
render(){
const { title, img, instructions } = this.props;
const ingredients=this.props.ingredients.map((ing,index)=>(<li key={index} >{ing}</li>));
return (
<div className='recipe-card'>
<div className='recipe-card-img'> <img src={img} alt={title}/> </div>
<div className='recipe-card-content'>
<h3 className='recipe-title'>Reciepe {title}</h3>
<ul> {ingredients} </ul>
<h4>Instructions:</h4>
<p>{instructions}</p>
</div>
</div>
)
}
}

parent 看起来像这样

class RecipeList extends Component{
render(){
return (
<div style={{'display':'flex'}}>
{this.props.recipes.map((item,index)=>(
<Recipe key={index}
title={item.title}
ingredients={item.ingredients}
instructions={item.instructions}
img={item.img}
/>
))}
</div>
)
}
}

关于javascript - 如何在 react.js 中将数据从父级传递给子级,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47483868/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com