2017-11-03 10 views
4

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() 
    }); 
}) 

기능 (이벤트 전) 반환 및 렌더링 :

답변

2

예, 그것은 바로 구성 요소 마운트하기 전에, 당신은 단순히 이벤트 리스너 ko를 추가하기 때문에, 렌더링됩니다.

getMemoryItems() { 
    if (this.state.memory) { 
     return <div> 
      <MemoryImage memory={this.state.memory}/> 
      <MemoryText memory={this.state.memory}/> 
     </div> 
    } 
} 

render(){ 
    return (
     <div> 
      <button type="button">Get Random Memory</button> 
      <h1>Memory App</h1> 
      { this.getMemoryItems() } 
     </div> 
    ); 
} 

또는 당신은 할 수 :

가장 간단한 솔루션 (IMO)가 될 것이다

render(){ 
    return (
     <div> 
      <button type="button">Get Random Memory</button> 
      <h1>Memory App</h1> 
      { this.state.memory ? <MemoryImage memory={this.state.memory}/> : '' } 
      { this.state.memory ? <MemoryText memory={this.state.memory}/> : '' } 
     </div> 
    ); 
} 
1
이유는 만 호출됩니다 componentWillMount에서 이벤트 핸들러를 등록하는 것입니다

그 사건이 언젠가 미래에 일어날 때 (즉, 귀하의 경우 init). componentWillMount은 등록 만하고 흐름을 계속 진행합니다 (예 : render 함수 등). 해당 이벤트가 발생하는 경우에만 memory 상태가됩니다. 당신이 memory 상태를 사용할 수있을 때까지 아무것도 렌더링하지 않으려면

그럼 당신은 단순히이

render(){ 
     if(!this.state.memory){ 
      // Just wait for the memory to be available 
      return null; 
     } 
     return (
      <div> 
       <button type="button">Get Random Memory</button> 
       <h1>Memory App</h1> 
       <MemoryImage memory={this.state.memory}/> 
       <MemoryText memory={this.state.memory}/> 
      </div> 
     ); 
    } 
같은 렌더링의 조건을 넣을 수 있습니다