Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/452.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 将道具从父级传递到子级,并将这些道具设置为状态不会立即起作用_Javascript_Reactjs_React State Management_React State - Fatal编程技术网

Javascript 将道具从父级传递到子级,并将这些道具设置为状态不会立即起作用

Javascript 将道具从父级传递到子级,并将这些道具设置为状态不会立即起作用,javascript,reactjs,react-state-management,react-state,Javascript,Reactjs,React State Management,React State,我正在构建一个应用程序,从我的Nodejs应用程序中获得“投诉”。然后我将这些投诉作为道具传递给子组件。在子组件中,我将这些道具设置为ComponentDidMount()中的状态。但是render()函数首先被调用,所以它不会在屏幕上显示任何内容。状态不会立即设置。请帮忙。我挣扎了两天 这是父组件 class Complainer extends Component { state = { complaints: [] }; async componentDidMount

我正在构建一个应用程序,从我的Nodejs应用程序中获得“投诉”。然后我将这些投诉作为道具传递给子组件。在子组件中,我将这些道具设置为
ComponentDidMount()
中的状态。但是
render()
函数首先被调用,所以它不会在屏幕上显示任何内容。状态不会立即设置。请帮忙。我挣扎了两天

这是父组件

class Complainer extends Component {
  state = {
    complaints: []
  };

  async componentDidMount() {
    try {
      const user = auth.getCurrentUser();
      console.log(user);
      this.setState({ user });
      if (!user || user.role !== 'complainer') this.props.history.replace('/');
    } catch (ex) {
      window.location = '/login';
    }

    const { data: complaints } = await getComplaints();
    this.setState({ complaints });
  }

  render() {
    const { complaints } = this.state;
    return (
      <React.Fragment>
        <Navbar user={this.state.user} />
        <div className="container">
          <Switch>
            <Route
              path="/complainer/view-all"
              render={props => (
                <AllComplaints complaints={complaints} {...props} />
              )}
            />
            <Route path="/complainer/new-complaint" component={ComplaintForm} />
            <Route path="/complainer/not-found" component={notfound} />
            <Showcase user={this.state.user} />
          </Switch>
          <hr />
        </div>
      </React.Fragment>
    );
  }
}

export default Complainer;

类投诉器扩展组件{
状态={
投诉:[]
};
异步组件didmount(){
试一试{
const user=auth.getCurrentUser();
console.log(用户);
this.setState({user});
如果(!user | | user.role!=='campiner')此.props.history.replace('/');
}捕获(ex){
window.location='/login';
}
const{data:complaints}=wait getComplaints();
本.集州({投诉});
}
render(){
const{complaints}=this.state;
返回(
(
)}
/>

); } } 出口违约投诉人;
这是我的孩子

class AllComplaints extends Component {
  state = {
    data: {
      columns: [
        {
          label: 'location',
          field: 'location',
          sort: 'asc',
          width: 280
        },
        {
          label: 'Title',
          field: 'title',
          sort: 'asc',
          width: 150
        }
      ],

      rows: []
    }
  };

  componentDidMount() {
    const { complaints } = this.props;
    this.setState({ rows: complaints });
  }

  render() {
    const { data } = this.state;
    return (
      <React.Fragment>
        {data.rows && <MDBDataTable striped bordered small data={data} />}
        {!data.rows && <h1>There is no complaints to show</h1>}
      </React.Fragment>
    );
  }
}

export default AllComplaints;
类所有组件{
状态={
数据:{
栏目:[
{
标签:'位置',
字段:'位置',
排序:“asc”,
宽度:280
},
{
标签:“标题”,
字段:“标题”,
排序:“asc”,
宽度:150
}
],
行:[]
}
};
componentDidMount(){
const{complaints}=this.props;
this.setState({rows:complaints});
}
render(){
const{data}=this.state;
返回(
{data.rows&&}
{!data.rows&&没有要显示的投诉}
);
}
}
出口违约投诉;
问题是,在状态中,行是空的。[]. 在
componentDidMount()
中,我正在将即将到来的道具设置为这个“AllComplaints”组件的状态

我想将“props”值设置为“this.state.data.rows”。但这并没有发生。设置需要时间,但会首先调用
render()
,因此在屏幕上不会显示任何内容


请提供帮助。

如果要在渲染功能期间使用投诉,需要在您的状态下对其进行初始化

您需要为类编写构造函数,从父组件接受道具,并使用它定义行的初始状态

class AllComplaints extends Component {

    constructor(props) {
        super(props);
        this.state  = {
            data: {
              columns: [
                {
                  label: 'location',
                  field: 'location',
                  sort: 'asc',
                  width: 280
                },
                {
                  label: 'Title',
                  field: 'title',
                  sort: 'asc',
                  width: 150
                }
              ],

              rows: props.complaints
            }
          };
        }
          componentDidMount() {
//commeting below lines as you do not need them as of now.
            //const { complaints } = this.props;
            //this.setState({ rows: complaints });
          }

          render() {
            const { data } = this.state;
            return (
              <React.Fragment>
                {data.rows && <MDBDataTable striped bordered small data={data} />}
                {!data.rows && <h1>There is no complaints to show</h1>}
              </React.Fragment>
            );
          }
        }

        export default AllComplaints;
类所有组件{
建造师(道具){
超级(道具);
此.state={
数据:{
栏目:[
{
标签:'位置',
字段:'位置',
排序:“asc”,
宽度:280
},
{
标签:“标题”,
字段:“标题”,
排序:“asc”,
宽度:150
}
],
行:道具
}
};
}
componentDidMount(){
//请在下面的行中输入逗号,因为您现在不需要它们。
//const{complaints}=this.props;
//this.setState({rows:complaints});
}
render(){
const{data}=this.state;
返回(
{data.rows&&}
{!data.rows&&没有要显示的投诉}
);
}
}
出口违约投诉;

您似乎没有设置
this.state.data.rows
而是
this.state.rows
并在渲染内部使用
this.state.data.rows
两件事:

正如@karahan提到的,你没有正确设置你的状态

this.setState({ rows: complaints });
应该是这样的:

this.setState(prevState => { data: { ...prevState.data, rows: complaints } });
然而,这可能还不够。您正在父级的
componentDidMount
中检索数据,并在子级的
componentDidMount
中设置状态。但是,如果同时装入子组件,则子组件的
组件didmount
始终首先运行,并且只运行一次。这意味着在您的设置中,您孩子的
道具.投诉
可能在
组件安装
中为空

我可以通过在孩子的组件中不使用状态来解决这个问题。很少有理由在多个组件中存储相同的状态(在本例中,您在父组件和子组件中存储相同的内容)。只需使用您的道具,它在渲染功能中始终是最新的。您对
MDBDataTable
的呈现可能如下所示:

<MDBDataTable striped bordered small data={{ ...this.state.data, rows: this.props.complaints }} />


如果出于某种原因,您必须将
投诉
存储在孩子的状态中,您应该取而代之的是在孩子的状态中获取数据,或者查看
getDerivedStateFromProps
componentdiddupdate
。但是,您不太可能需要这样的设置。

在此处使用状态有什么特殊原因吗?为什么不直接使用
?另外,在哪里检索数据?它是否在父级的
组件didmount
中?如果是这样,您应该在问题中包括父级的
组件didmount
呈现
函数。我现在已经包括了父级。请看一看。这对我有用。谢谢你,伙计!非常感谢