我有一个渲染之外的函数。该函数(有条件地)返回一个组件,该函数不是在渲染内部触发,而是在 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:""};
}
现在,在 render()
中使用 {this.getdata}
和 {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/