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()
에서 이후의 상태를 설정합니다. 그런 다음 구성 요소를 렌더링하려고합니다. 구성 요소 중 하나는 image
입니다 : 가져 오기가
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>
);
}
}
를 '반응'에서 그리고 콘솔에 로그인 한 후 반작용 ...
memory-image.js:10 {memory: undefined}
memory-image.js:10 {memory: Array(1)}
내가 설정하기 전에 구성 요소가 렌더링 나에게 나타납니다 componentWillMount()
함수의 상태입니다. 저는 이것을 원하지 않습니다. 단지 상태가 componentWillMount()
으로 설정된 후에 컴포넌트를 렌더링하기를 원합니다. 어떤 아이디어?
MemoryStore.on("init",() => {
this.setState({
memory: MemoryStore.getInit()
});
})
기능 (이벤트 전) 반환 및 렌더링 :