ReactJでコンポーネントをレンダリングする前に、いくつかの初期データをロードしようとしています。 このプロセスでは、Flux
アーキテクチャも使用しています。ここに私のcontainer
です:ComponentWillMountの前にレンダリングが発生する
class MemoryApp extends React.Component {
constructor(props){
super(props);
MemoryActions.getInit();
this.state = {};
}
componentWillMount(){
MemoryStore.on("init",() => {
this.setState({
memory: MemoryStore.getInit()
});
})
}
render(){
return (
<div>
<button type="button">Get Random Memory</button>
<h1>Memory App</h1>
<MemoryImage memory={this.state.memory}/>
<MemoryText memory={this.state.memory}/>
</div>
);
}
}
ので、このファイルには、私はいくつかのデータを取得するAPIを呼び出すアクションgetInit()
を呼び出しています。このデータが受信されると、init
イベントがstore
によって放出される。
class MemoryStore extends EventEmitter {
getInit(){
return this.memory_response;
}
initLoad(response){
this.memory_response = response;
this.emit("init");
}
handleActions(action){
switch (action.type) {
case MemoryConstants.GET_INIT_RESPONSE:{
this.initLoad(action.response);
break;
}
default:{
return true;
}
}
}
}
const memoryStore = new MemoryStore();
dispatcher.register(memoryStore.handleActions.bind(memoryStore));
export default memoryStore;
次に、あなたが見ることができるように、我々はcomponenWillMount()
で、その後の状態を設定します。次に、コンポーネントをレンダリングします。コンポーネントの1つがimage
です: インポートは私が設定する前にコンポーネントがレンダリングされているように私には見える
memory-image.js:10 {memory: undefined}
memory-image.js:10 {memory: Array(1)}
...
export default class MemoryImage extends React.Component{
renderItems(){
console.log(this.props); // ===> Here is my console.log
if (this.props.memory){
return this.props.memory[0].description;
} else {
return "Nothing";
}
}
renderImage(){
if (this.props.memory){
return this.props.memory[0].image;
} else {
return "Nothing";
}
}
render(){
return(
<div>
<p>{this.renderItems()}</p>
<img style={{width:'200px'}} src={this.renderImage()} alt="none"/>
</div>
);
}
}
そして、コンソールにログインした後に「反応」からリアクトcomponentWillMount()
の状態です。私はこれを望んでいない、私は状態がcomponentWillMount()
に設定された後にコンポーネントをレンダリングするだけです。何か案は?
MemoryStore.on("init",() => {
this.setState({
memory: MemoryStore.getInit()
});
})
機能(イベントの前に)戻り、レンダリング: