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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/47483868/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-29 07:24:26  来源:igfitidea点击:

How to pass data from parent to child in react.js

javascriptreactjsredux

提问by pKay

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?

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

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

在下面的代码中,如果我在 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>
            )
    }
}

回答by HimanshuArora9419

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.

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

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

回答by Brijesh Bhakta

The problem is that you are assigning the values to this which is not a good practice. Check where to declare variable in React here.

问题是您正在为此分配值,这不是一个好习惯。在此处检查在 React 中声明变量的位置。

If you are not using the props to do any complex operations. This should work.

如果你不使用道具来做任何复杂的操作。这应该有效。

EmpList Componet

import React, {Component} from 'react'

export default class Emp extends Component {

    constructor(props) {
        super(props);
    }

    render() {

        if (!this.next)
            return <div>name not found</div>;
        else
          return (
              <div>
                  <br/>
                  <p>The list is here</p>
                  <ul>
                      {this.props.emp && this.props.emp.map(e => <li>{e.name}</li>)}
                  </ul>
              </div>
            )
    }
}

回答by Shubham Khatri

Your next and emplist class properties are directly derivable from your props and hence you don't actually need them. You could do it in the following way

您的 next 和 emplist 类属性可直接从您的 props 派生,因此您实际上并不需要它们。您可以通过以下方式进行

import React,{Component} from 'react'

export default class Emp extends Component{

    render(){
        const { emp } = this.props;
        if(!emp || emp.length === 1)
            return <div>name not found</div>
        else {
           return (
              <div> 
                 <br/> <p>The list is here</p>
                 <ul>
                   {emp.map(e=>{return <li>{e.name}</li>});}
                 </ul>
              </div>
           )
       }
    }
}


However in cases when you do what to make really complex decisions based on props, a combination of componentWillReceivePropsand componentDidMount/componentWillMountis the right place to do it.

但是,如果您要根据道具做出真正复杂的决定,那么结合componentWillReceivePropscomponentDidMount/componentWillMount是正确的做法。