为什么我的this.props.data在渲染函数之前的任何地方都未定义?

时间:2019-02-10 22:54:24

标签: reactjs react-props react-state-management

数据正从父级传递到子级,因此它在render函数中显示,但是我无法将其用于异步函数,该函数需要在render之前运行。

如果您在渲染功能下看到data.titledata.link的所有昭和,但由于某些原因,它们显示此错误:

× TypeError: Cannot read property 'link' of null

我还可以做什么?

 export default class Highlight extends Component {

state = {
    htmlString: ''
}

 fetchActivity = () => {

    axios({
        method: 'post',
        url: 'api/singleactivity',
        data: { activityLink: "http://play.fisher-price.com" + this.props.data.link }
    })
        .then((res) => {
            this.setState({
                htmlString: res.data
            })
        })
        .catch((err) => {
            console.log('There was an error fetching data', err);
        })

}

componentDidMount() {
    this.fetchActivity()
}

 render() {

    if (this.props.visibility.highlight) {

        return (
            <div>
                <section className="card bg-info"
                    aria-label="Book Detail">
                    <div className="bg-secondary">
                        <h2>{this.props.data.title}</h2>
                        <h2>{this.props.data.link}</h2>
                        <h2>{this.props.data.imageLink}</h2>
                    </div>
                    <br />
                    <div className="row" dangerouslySetInnerHTML={{ __html: this.state.htmlString }}>
                    </div>
                    <br />
                    <div className="bg-warning">
                        {!this.props.visibility.favorites ?
                            <button onClick={() => this.addToFavorites()}> Favorite</button> :
                            <button onClick={() => this.removeFromFavorites()}> Remove</button>}
                    </div>
                </section>
                <br />
            </div>
        )
    } else {
        return null;
    }

}

2 个答案:

答案 0 :(得分:0)

您可以做的是:

filter

答案 1 :(得分:0)

好吧,混合使用提取调用和查看代码,或者分开使用危险地设置InnerHTML,道具IPAddress ipAddress = ipHostInfo.AddressList[0]; C:\> telnet 10.x.x.x 11000 并不总是拥有值,这是问题的直接根源。

因此,您可以肯定地以this.props.data的方式使用组件,可以将其更改为<Highlight data={stuff} ... />之类,这样,如果输入数据尚未准备好,就不会首先创建组件。