如何在 react.js 中将数据从父级传递给子级 [英] How to pass data from parent to child in react.js

查看:24
本文介绍了如何在 react.js 中将数据从父级传递给子级的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

import React, { Component } from 'react';从 './search-bar' 导入 {Search}从'./emplist'导入Emplist类 App 扩展组件 {构造函数(道具){超级(道具);this.emp=[{name:'pawan',年龄:12},{name:'manish',年龄 : 11}]this.state={emp:this.emp};this.filterResults=this.filterResults.bind(this);}过滤结果(val){如果(这个状态){让过滤=[];过滤推(this.emp.find(e=>{返回 e.age==val}));this.setState({emp:filt});}}使成为() {返回 (<div className="应用程序"><搜索过滤结果={this.filterResults}/><Emplist emp={this.state.emp}/>

);}}导出默认应用;

EmpList 组件从反应"导入反应,{组件}导出默认类 Emp 扩展组件{构造函数(道具){超级(道具);this.emplist=this.props.emp.map(e=>{return 
  • {e.name}
  • });this.next=this.emplist;}componentWillReceiveProps(nextProps,nextState,prevProps,prevState,nextContext,prevContext){//this.props.updated(this.props.empo);this.next=nextProps.emp[0];如果(这个.下一个)this.emplist= nextProps.emp.map(e=>{return
  • {e.name}
  • });}使成为(){如果(!this.next)返回

    未找到名称

    别的返回 (<div><br/><p>列表在这里</p><ul>{this.emplist}

    )}}

    解决方案

    如果你想从父级传递给子级,你可以使用 props 传递,如果你想做反向,你可以将一个函数从父级传递给子级和而不是使用此传递的函数将某些内容发送回父级.

    孩子看起来像这样

    class Reciepe 扩展组件{使成为(){const { 标题、图片、说明 } = this.props;const成分=this.props.ingredients.map((ing,index)=>(<li key={index} >{ing}</li>));返回 (<div className='recipe-card'><div className='recipe-card-img'><img src={img} alt={title}/>

    <div className='recipe-card-content'><h3 className='recipe-title'>食谱{title}</h3><ul>{成分} </ul><h4>说明:</h4><p>{指令}</p>

    )}}

    父母看起来像这样

    class RecipeList 扩展组件{使成为(){返回 (<div style={{'display':'flex'}}>{this.props.recipes.map((item,index)=>(<配方键={索引}标题={item.title}成分={item.ingredients}说明={item.instructions}img={item.img}/>))}

    )}}

    I have a parent component which has 1 child. I am updating my child by passing data through props. initially, it works fine but when I click on a button and update the state using setState the child gets rendered with old values by the time setState is finished. I have solved it using componentWillReceiveProps in the child but is this the right way?

    In the below code if I do setState in filterResults function it won't update the Emplist component .

    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>
                )
        }
    }

    解决方案

    If you want to pass from parent to child you can pass using props and if you wan t to do reverse than you can pass one function from parent to child and than use this passed function to send something back to parent.

    child will look something like this

    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 will look something like this

    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>
            )
        }
    }
    

    这篇关于如何在 react.js 中将数据从父级传递给子级的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

    查看全文
    相关文章
    前端开发最新文章
    热门教程
    热门工具
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆