我需要创建一个元素,在渲染时加载自己的数据并显示它。我写了这样的话:
export default class MyComponent extends React.Component {
constructor() {
super();
this.state = {
content: "Loading..."
};
}
render() {
Data.singleton().load(0, 100, "desc").then((function(data) {
this.setState({
content: {JSON.stringify(data, null, 3)}
});
}).bind(this));
return <pre>{this.state.content}</pre>
}
}
现在,这有效,但反应文件明确指出:
render()函数应该是纯的,这意味着它不会修改 组件状态
所以我想知道这种需求的最佳设计模式是什么。
p.s:我知道我可以在包含元素中加载数据并使用props将其传递给MyComponent
。我也知道这似乎是&#34;方式&#34;和我一起做出反应,但我想知道是否有其他合法的方法。
谢谢
答案 0 :(得分:2)
以下是一个示例:JSFiddle
这应该在componentDidMount
中处理(请注意,我使用setTimeout
来模拟异步调用):
class Main extends React.Component{
constructor(props){
super(props);
this.state = {
data: 'Loading...'
}
}
componentDidMount() {
console.log('Mounted');
setTimeout(() => {
this.setState({
data: 'set after waiting 2 seconds'
})
}, 2000)
}
//
render() {
return (
<div>{this.state.data}</div>
);
}
}
答案 1 :(得分:0)
看起来您需要做的就是将该功能投入componentDidMount
或componentWillMount
,如下所示:
componentDidMount() {
// state-altering logic
}
render() {
return <pre>{this.state.content}</pre>
}
https://facebook.github.io/react/docs/component-specs.html#mounting-componentwillmount
答案 2 :(得分:0)
因为它建议在componentDidMount中使用你的ajax方法 https://facebook.github.io/react/docs/component-specs.html#mounting-componentdidmount 你可以像这样构建你的反应组件
export default class MyComponent extends React.Component {
constructor() {
super();
this.state = {
content: "Loading..."
};
}
componentDidMount(){
Data.singleton().load(0, 100, "desc").then((data)=> {
this.setState({
content: {JSON.stringify(data, null, 3)}
});
});
}
render() {
return <pre>{this.state.content}</pre>
}
}