0

数据相应地从父级传递到子级,因此它显示在渲染函数中,但我无法将它用于我需要在渲染之前运行的异步函数。

如果您在 render 函数下看到data.titleand data.linkall showa 但由于某种原因它们显示此错误:

× 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;
    }

}
4

2 回答 2

0

你可以做的是:

{this.props.data ? this.props.data.title : ''}

{this.props.data ? this.props.data.link: ''}
于 2019-02-10T22:58:39.827 回答
0

好吧,混合 fetch 调用和查看代码或分开使用 dangerouslySetInnerHTML,你的 propthis.props.data并不总是持有一个值,这是你问题的直接来源。

因此,您可以肯定地以这种方式使用您的组件,<Highlight data={stuff} ... />您可以将其更改为类似的东西{stuff ? <Highlight data={stuff} ... /> : null},如果输入数据尚未准备好,则不会首先创建该组件。

于 2019-02-10T23:11:50.643 回答