ReactJS:有条件地渲染多个组件

时间:2018-03-16 18:58:06

标签: reactjs ecmascript-6

所以,我有一些组件传递一个函数来更新主要组件的状态,然后我想重新渲染孙子组件......

class GrandParentComponent extends Component {
  state = {
    formData: {
      rooms: [],
    },
  }

// has a function: handleRoom
handleRoom = room => {
  let roomsArray = this.state.formData.rooms.slice();
  let newRooms = [...roomsArray, room]; // add room to array
  this.setState({
    formData: update(this.state.formData, { rooms: { $set: newRooms }}),
  }); // update and $set comes from 'immutability-helper'
}
</GrandParentComponent>

Passes down to ParentComponent
<ParentComponent handleRoom={this.handleRoom} formData={this.state.formData} />

Passes down to ChildComponent
<ChildComponent handleRoom={this.props.handleRoom}  />

In thie child component, I want to update the state of the grandparent component.

handleSaveRoom = room => { this.props.handleRoom(room); }
// great this successfully updates the grandparent...

更新祖父组件后,我想使用新数据重新渲染ParentComponent:

<ParentComponent handleRoom={this.handleRoom} formData={this.state.formData} >

handleCreateAddRoomForm = (room, i = 0) => {
  return (
    <Panel header={room.title} key={i}>
      <AddRoomForm room={room} />
    </Panel>
   )
}

render() {
  const { formData } = this.props;
  const renderRooms = formData.rooms.length 
    ? formData.rooms.map((room, i) => {
      this.handleCreateAddRoomForm(room, i);
    })
    : this.handleCreateAddRoomForm({title: 'New Room'});

  return (
    <div>
      {renderRooms}
    </div>
  )
 }
</ParentComponent>

所以,我找回了房间......不确定(13未找到)......但<Panel />中未显示<ParentComponent />

理想情况下,当<Grandparent /> <Child />更新数据时,<Parent />应创建<Panel />组件以显示更改...

思考?

1 个答案:

答案 0 :(得分:1)

您的地图功能必须返回undefined。您的formData.rooms.map不会返回任何内容。

const renderRooms = formData.rooms.length 
  ? formData.rooms.map((room, i) => {
    this.handleCreateAddRoomForm(room, i);
  })
  : this.handleCreateAddRoomForm({title: 'New Room'});

尝试这样做(请注意我是如何删除地图中的{ }的)。如果您想保留{ },请确保返回值。

const renderRooms = formData.rooms.length 
  ? formData.rooms.map((room, i) => this.handleCreateAddRoomForm(room, i))
  : this.handleCreateAddRoomForm({title: 'New Room'});

const renderRooms = formData.rooms.length 
  ? formData.rooms.map((room, i) => {
    return this.handleCreateAddRoomForm(room, i);
  })
  : this.handleCreateAddRoomForm({title: 'New Room'});