首页 > 解决方案 > ReactJS - 将状态传递给在构造函数中为空的组件

问题描述

我试图将状态作为道具传递给子组件,当状态传递时,构造函数内的道具和子组件的 componentDidMount 为空。但是在渲染方法中,道具不是空的

我的父组件:项目

import React, { Component } from 'react';
import { NavLink } from 'react-router-dom';
import NewTask from '../../../TaskList/NewTask/NewTask';
import Tasks from '../../../TaskList/Tasks/Tasks';
import './Project.css';

class Project extends Component {
    constructor(props) {
        super(props);
        console.log("props received = " + JSON.stringify(props));
        this.state = {
            project: {}
        };
    }

    componentDidMount() {
        const { match: { params } } = this.props;

        fetch(`/dashboard/project/${params.id}`)
            .then(response => {
                return response.json()
            }).then(project => {
                this.setState({
                    project: project
                })
                console.log(project.tasks)
            })
    }


    render() {
        return (
            <div>
                <section className='Project container'>
                    <NewTask projectId={this.state.project._id} />
                    <br />
                    <h4>Coming Soon ...</h4>
                    <Tasks projectId={this.state.project._id} />
                </section>
            </div>
        );
    }
  }

export default Project;

例如,在这个组件中,道具被正确渲染,但在构造函数和 componentDidMount() 中是空的。

我的子组件:任务

  import React, { Component } from 'react';
  import { NavLink } from 'react-router-dom';
import './Tasks.css';

    class Tasks extends Component {
        constructor(props) {
            super(props);
            // There are empty
            console.log(JSON.stringify(props.projectId));
            this.state = {
                projectId: props._id,
                tasks: []
            };
        }

        componentDidMount() {
            // These are empty too ...
            console.log(JSON.stringify(this.props));    
        }

        render() {
            return (
                <div>
                    // These aren't empty
                    {this.props.projectId}
                </div>
            );

        }
    }

    export default Tasks;

标签: reactjscomponentsstatereact-props

解决方案


解决此问题的最简单方法是向 Project 组件添加条件:

{this.state.project &&
  this.state.project._id &&
  <Tasks projectId={this.state.project._id} />
}

另一种方法是在任务组件中执行此操作:

constructor(props) {
    super(props);
    this.state = {
        projectId: props._id,
        tasks: []
    };
}

componentDidUpdate(prevProps, prevState, snapshot) {
  // compare this.props and prevProps
  if (this.props !== prevProps) {
      this.setState({
          projectId: this.props._id
      });
  }
}

render() {
    return (
        <div>
            {this.state.projectId}
        </div>
    );
}

推荐阅读