gpt4 book ai didi

javascript - React - 如何在渲染外部的函数内渲染组件并在渲染外部执行相同的函数?

转载 作者:行者123 更新时间:2023-11-30 09:23:36 25 4
gpt4 key购买 nike

我有一个渲染之外的功能。该函数(有条件地)返回一个组件,该函数不是在渲染内部触发,而是在 componentWillReceiveProps 内部触发(由于其他事实,这是必需的)。我的问题是函数最终没有返回组件,我不知道为什么。当我在 render 中调用该函数时,它会起作用,但我不能这样做,因为我必须在 componentWillReceiveProps 中调用它。有任何想法吗?谢谢!!

class App extends React.Component {
componentWillReceiveProps(nextProps) {
if (nextProps.user != this.props.user) {
this.getData(nextProps.user)
}
}

getData() {
if (...) {
return <Child />
}
}

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

const Child = () => {
return <h1>Hello</h1>
}

最佳答案

在构造函数中创建一个名为data的状态如下:

constructor(props){
super(props);
this.state={data:""};
}

现在,{this.getdata} inside render() with {this.state.data}

同样替换componentWillReceiveProps如下:

componentWillReceiveProps(nextProps) {
if (nextProps.user != this.props.user) {
var newdata = this.getData(nextProps.user)
this.setState({data:newdata});
}
}

关于javascript - React - 如何在渲染外部的函数内渲染组件并在渲染外部执行相同的函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50154479/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com