ReactJS道具未加载在componentWillMount和componentDidMount中

问题描述

对于我的React-Select集成,我具有以下代码,并且需要在第一次渲染之前将b字段设置一次。

selectedOption

还有一些控制台输出

import React from 'react';
import Select from 'react-select';
 
interface IOption{
    value:string,label:string
}

interface Props{
    data : IOption[],onSelected : (id:string) => void
}

export default class ReactSelect extends React.Component<Props> {
    constructor(props){
        super(props)
        console.log("data from constructor : ",this.props.data)
    }

    tempSelectedOption:IOption | undefined
    state = {
        selectedOption:this.tempSelectedOption,};  

    componentWillMount(){
        this.setState({ selectedOption : this.props.data[0]},()=>{console.log("component will mount meth:",this.state.selectedOption)})
        console.log("data from componentWillMount : ",this.props.data)
    }

    componentDidMount(){
        this.setState({ selectedOption : this.props.data[0]},()=>{console.log("component did mount meth:",this.state.selectedOption)})
        console.log("data from componentDidMount : ",this.props.data)
    }

    handleChange = selectedOption => {
        this.setState({ selectedOption });
        this.props.onSelected(selectedOption.value)
        console.log(`Option selected:`,selectedOption);
    };

    render() {
        const{ selectedOption } = this.state;
        console.log("props.data in render :",this.props.data)

        return (
            <Select
                value = {selectedOption}
                onChange = {this.handleChange}
                options = {this.props.data}
            />
        );
    }
}

解决方法

Ciao,我不是打字稿爱好者,但我认为您的问题可能与如何将道具传递到ReactSelect组件有关。

我做了这个(非常愚蠢)example,道具记录似乎起作用了:

App组件中:

...
<Child data={"ciao"} />
...

然后是Child组件:

class Child extends React.Component<{}> {
  constructor(props) {
    super(props);
    console.log("data from constructor : ",this.props.data)
  }

  componentDidMount() {
    console.log("data from componentDidMount : ",this.props.data);
  }

  private handleClick = (event: React.MouseEvent<HTMLButtonElement>) => {
    const type: string = event.currentTarget.title;

    this.setState(({ count }) => ({
      count: type === "decrement" ? count - 1 : count + 1
    }));
  };

  public render() {
    console.log("props.data in render :",this.props.data);
    return (
      ...
    );
  }
}

日志显示:

data from constructor :  ciao 
props.data in render : ciao 
data from componentDidMount :  ciao 
,

首先,我要感谢关注此问题的每个人。

我也评论了@GiovanniEsposito的回答,情况大致如下,

在父组件中包含一个sdk,问题是我想将data [0]呈现为默认值,但是props.data在bsf 1之后加载。实际上,即使在第一次渲染函数调用之后,仍会返回sdk服务调用,因此,在更新props.data时,需要使用其他渲染方法。然后'0'仅在componentWillMount函数中可用,因此我不得不在componentDidMount函数中处理问题。

我将props.data修改为

render

结果,我解决了我的问题,但我有一个警告,目前看来这对我来说并不严重。如果我做错了什么,请警告我:)

render

相关问答

依赖报错 idea导入项目后依赖报错,解决方案:https://blog....
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下...
错误1:gradle项目控制台输出为乱码 # 解决方案:https://bl...
错误还原:在查询的过程中,传入的workType为0时,该条件不起...
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct...