2016-10-29 4 views
0

몇 가지 메시지가있는 방이 있습니다. 그래서이 모델은렌더링 방법은 2 번만 반응합니다.

{ 
    createdAt: Date, 
    messages: [String] 
} 

내가

class Room extends React.Component { 
    constructor(props) { 
    super(props); 
    this.state = { room: {} }; 
    } 

    componentDidMount() { 
    this.fetchRoom(); 
    } 

    componentDidUpdate(prevProps) { 
    let oldId = prevProps.params.roomId 
    let newId = this.props.params.roomId 
    if (newId !== oldId) { 
     this.fetchRoom(); 
    } 
    } 

    componentWillUnmount() { 
    this.ignoreLastFetch = true; 
    } 

    fetchRoom() { 
    if (!this.ignoreLastFetch) { 
     const roomId = this.props.params.roomId; 
     socket.emit('get room', roomId, room => { 
     this.setState({ room: room }); 
     }); 
    } 
    } 

    render() { 
    console.log(this.state.room.messages); // debug 

    const roomId = this.state.room._id; 
    return (
     <div> 
     <h2>Id: {roomId}</h2> 
     <p>Created at: {this.state.room.createdAt}</p> 
     <h2>Messages</h2> 
     <Messages roomId={roomId} messages={this.state.room.messages} /> 
     </div> 
    ); 
    } 
} 

내 방을 페치 문제는 render() 모두가 내가 방을 인출 한 후 방 을 가져왔다 전에 , 소위 때문이다 2 건의 전화가 걸립니다.

빈 방을 보지 않아도 방을 가져올 때까지 render 번을 기다릴 수 있습니까?

<Messages roomId={roomId} messages={this.state.room.messages} />을 사용하고 있기 때문에 메시지 배열이 비어있는 것으로 보입니다. render() 메소드에서 console.log(this.state.room.messages)으로 디버깅하면 먼저 정의되지 않은 내용이 인쇄 된 다음 메시지 배열 (즉 2 건)이 인쇄됩니다.

+1

반응이있을 때 렌더링은 구성 요소가 마운트 된 직후 (또는?)에 호출되고 setState를 호출 한 후에 호출됩니다. 그건 정상입니다. –

답변

2

메서드 render은 구성 요소가 탑재 된 후에 호출되지만 필요한 데이터가있을 때까지 구성 요소를 렌더링하지 않는 방법이 있습니다.

당신도 null 또는 false 당신이 렌더링 아무것도하지 않는 것을 나타 내기 위해 반환 할 수 있습니다 React documentation는이 문제를 해결하는 방법을 정의합니다.

의이 렌더링 방법이 활용하자 :

render() { 
    // check if the room is set 
    if(!this.state.room){ 
     // room is not set, return null so that nothing is rendered 
     return null; 
    } 

    // happy path - render the room 
    const roomId = this.state.room._id; 
    return (
     <div> 
     <h2>Id: {roomId}</h2> 
     <p>Created at: {this.state.room.createdAt}</p> 
     <h2>Messages</h2> 
     <Messages roomId={roomId} messages={this.state.room.messages} /> 
     </div> 
    ); 
    } 
0

당신은 "shouldComponentUpdate"이 논리를 배치하지 렌더링 메서드 내에서해야한다. 렌더링 메소드는 순수해야하며 그 안에 로직을 배치하면 안됩니다. 또한 Component에서 null을 반환하면 가상 돔에 사이트 효과가있을 수 있습니다.

+0

'render'보다는'shouldComponentUpdate'에 어떤 로직을 넣어야합니까? 'null'을 반환하는 다른 방법이 있습니까? – Jamgreen

+0

shouldComponentUpdate가 true를 반환 할 경우 render 메서드가 호출됩니다. 이렇게하면 이전 소품에 대한 간단하고 복잡한 점검을 수행 할 수 있습니다. 변경으로 "실제"dom에 쓰기가 필요하다는 것을 안다면 "true"를 반환 할 수 있습니다. 이것은 React가 렌더링되지 않음을 의미합니다. –

관련 문제