ReactJS - Дочерние реквизиты не обновляются, когда дочерние элементы отображаются через переменную - PullRequest
0 голосов
/ 11 мая 2018

Моя цель - визуализировать разные компоненты через this.state.currentpage .Все работает, как и ожидалось, кроме случаев, когда мне нужно обновить реквизит отрендеренного компонента.Это проблема, потому что teamList постоянно меняется.У меня teamList обновлены текущие изменения, но я не могу получить изменения в компоненте, хранящемся в this.state.currentpage .

class ManagerTeam extends Component {

  constructor(props) {
    super(props)
    this.initComponent = this.initComponent.bind(this)
    this.showTeamMembros = this.showTeamMembros.bind(this)
    this.showTeamReport = this.showTeamReport.bind(this)
    this.showTeamTarefas = this.showTeamTarefas.bind(this)
    this.showVisaoGeral = this.showVisaoGeral.bind(this)
    this.updateData = this.updateData.bind(this)
    this.initComponent()
  }

  initComponent() {
    this.updateData(this.props)
    this.state = {
      currentpage: <ManagerTeamVisaoGeral teamList={this.teamList}/>
    }
  }

  updateData(props) {
    this.teamList = props.userTeams.list
  }

  showTeamMembros() {
    this.setState({
      currentpage: <ManagerTeamMembros/>
    })
  }

  showTeamReport() {
    this.setState({
      currentpage: <ManagerTeamReport/>
    })
  }

  showTeamTarefas() {
    this.setState({
      currentpage: <ManagerTeamTarefas/>
    })
  }

  showVisaoGeral() {
    this.setState({
      currentpage: <ManagerTeamVisaoGeral teamList={this.teamList}/>
    })
  }

  componentWillReceiveProps(nextProps) {
    this.updateData(nextProps)
  }

  render() {
    return (
      <div>
        <SimpleNavBar user={this.props.user} updateArtifacts={this.props.updateArtifacts} updateManagerTeams={this.props.updateManagerTeams}/>
        <NavBar navBarTitle='Equipas' menuOptions={['Visão Geral', 'Membros', 'Tarefas', 'Report']} loadOptions={[this.showVisaoGeral, this.showTeamMembros, this.showTeamTarefas, this.showTeamReport]}/>
        <Sidebar activePage="team" isManager={true}/>
        {this.state.currentpage}
      </div>
    )
  }

}

Ответы [ 2 ]

0 голосов
/ 11 мая 2018

Это потому, что вы обновляете список, но ваш компонент больше не рендерится.Поэтому лучше иметь teamList как state variable и делать this.setState, когда вы обновляете список, и еще одна вещь - попытаться иметь условие if в вашем componentWillReceiveProps что-то вроде этого:

componentWillReceiveProps(nextProps) {
 if(this.state.teamList !== nextProps.userTeams.list){
  // update will be called only when you have new list
  this.updateData(nextProps)
  }
 }
0 голосов
/ 11 мая 2018

Ваш реквизит компонента, отображаемого переменной состояния, не обновляется, поскольку переменная не обновляется при каждом отображении, а только при вызове setState,

Вместо этого следует отображать страницы условно или использовать маршрутизатор.Также вы можете просто включить обработчик и передать ему страницу, для которой он нужен, в качестве параметра

При условном рендеринге ваш код будет выглядеть как

class ManagerTeam extends Component {

  constructor(props) {
    super(props)
    this.initComponent = this.initComponent.bind(this)
    this.showPage = this.showPage.bind(this)
    this.initComponent()
  }

  initComponent() {
    this.updateData(this.props)
    this.state = {
      currentpage: <ManagerTeamVisaoGeral teamList={this.teamList}/>
    }
  }

  updateData(props) {
    this.teamList = props.userTeams.list
  }

  showPage(page) {
    this.setState({
      currentpage: page
    })
  }


  componentWillReceiveProps(nextProps) {
    this.updateData(nextProps)
  }

  render() {
    return (
      <div>
        <SimpleNavBar user={this.props.user} updateArtifacts={this.props.updateArtifacts} updateManagerTeams={this.props.updateManagerTeams}/>
        <NavBar navBarTitle='Equipas' menuOptions={['Visão Geral', 'Membros', 'Tarefas', 'Report']} loadOptions={[this.showVisaoGeral, this.showTeamMembros, this.showTeamTarefas, this.showTeamReport]}/>
        <Sidebar activePage="team" isManager={true}/>
        {this.state.currentpage === 'Visão Geral' && <ManagerTeamVisaoGeral teamList={this.teamList}/>}
        {this.state.currentpage === 'Membros' && <ManagerTeamMembros/>}
        {this.state.currentpage === 'Tarefas' && <ManagerTeamTarefas/>}
        {this.state.currentpage === 'Report' && <ManagerTeamReport/>}

      </div>
    )
  }
}
...