为什么我的孩子React组件需要被包装在函数内以检测父状态变化?

时间:2017-01-20 10:34:28

标签: reactjs

这是我的工作代码,下面是我希望我的代码看起来像但不起作用的代码:

我希望我的MainComponent的selectDay方法更改TableComponent的url以根据选择的日期获取数据

class MainComponent extends React.Component{

constructor(props) {
    super(props);
    this.state = {
        urls: [{
            appointmentsUrl: "/api/appointments",
            callsUrl: "/api/calls"
        }]
    }
}

selectDay(day) {
    if(day.key == 1) {
        this.setState({
            urls: [{
                appointmentsUrl: "/api/appointments",
                callsUrl: "/api/calls"
            }]
        })
    } else {
        this.setState({
            urls: [{
                appointmentsUrl: "/api/appointments2",
                callsUrl: "/api/calls2"
            }]
        })
    }
}

    render() {
    var calendarData = [//init some array of dates];


    return (
        <div>
            <TopMenuComponent/>
            <div className="contentContainer">
                {
                    ((urls)=>{
                        return(
                            <TableComponent key={urls[0].appointmentsUrl} appointmentsUrl={urls[0].appointmentsUrl} callsUrl={urls[0].callsUrl}/>
                        )
                    })(this.state.urls)
                }
            </div>
        </div>
    )
}

这有效,但我想要的是类似的东西:

<TableComponent appointmentsUrl={this.state.appointmentsUrl} callsUrl={this.state.callsUrl}/>

并将状态初始化为:this.state= {appointmentsUrl: "/api/appointments", callsUrl: "/api/calls"}

1 个答案:

答案 0 :(得分:0)

如果您在问题中表示的结构中有自己的状态,并且您想要使用该数组中的第一个对象(假设您启用了解构语法):

function render() {
  const [firstUrlObj] = this.state.urls
  return (
    <div>
      <TopMenuComponent/>
      <div className="contentContainer">
        <TableComponent appointmentsUrl={firstUrlObj.appointmentsUrl} callsUrl={firstUrlObj.callsUrl}/>
      </div>
    </div>
  )
}

如果要渲染整个数组:

function render() {
  const urls = this.state.urls
  return (
    <div>
      <TopMenuComponent/>
      <div className="contentContainer">
        { urls.map(urlObj => <TableComponent appointmentsUrl={urlObj.appointmentsUrl} callsUrl={urlObj.callsUrl}/>) }
      </div>
    </div>
  )
}

如果你在阵列中有一个对象并且你不打算有更多的对象,我建议你看另一个答案。