【问题标题】:How to pass data from parent to child in react.jsreact.js中如何将数据从父级传递给子级
【发布时间】:2017-11-25 08:08:36
【问题描述】:

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

在下面的代码中,如果我在 filterResults 函数中设置状态,它不会更新 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>
            )
    }
}

【问题讨论】:

  • 是的,这是正确的方法。如果您不需要将这些值用于某些复杂的事情或孩子的其他任何事情,您可以直接将它们与this.props.someValue 一起使用。
  • 在孩子中,我使用了 nextProps,因为当孩子渲染时我无法获得更新的道具。 this.props.someValue 将如何在 child 中工作?
  • 你能给出你的子组件的完整代码吗?这将很容易。请使用代码更新您的问题。
  • 使用 Redux 会很有帮助并且没有压力。当您有多个路线时,传统的参数传递方法有时会很忙。
  • @pKay 给出了答案。请检查。

标签: javascript reactjs redux


【解决方案1】:

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

孩子看起来像这样

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

父母看起来像这样

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

【讨论】:

  • 您在 Recipe 组件中传递了一些属性。这将第一次起作用,但是当我使用 setState 更新其中一个属性(即您的情况下的标题)时,子组件将使用旧道具呈现,因为 setState 是异步的,因此需要时间来更新。那么我们如何解决这个问题。我也发布了代码。你可以看看
【解决方案2】:

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

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

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

【讨论】:

    【解决方案3】:

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

    但是,如果您根据道具做出非常复杂的决定,componentWillReceivePropscomponentDidMount/componentWillMount 的组合是正确的选择。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-08-03
      • 2020-09-22
      • 1970-01-01
      • 2017-11-07
      • 2011-09-07
      • 2018-03-09
      • 2023-03-13
      • 1970-01-01
      相关资源
      最近更新 更多