状态未与componentWillMount一起安装

时间:2019-07-08 17:07:56

标签: reactjs antd

我有一个treenode,我试图在用户选择一个节点后显示内容,但是内容没有改变。

 constructor(props) {
    super(props);

    this.state = {
      t:["",""],
      loading: false,
      disPageTken:"",
    };
  }
  componentWillMount(){

     window.FB.api(
    '/me',
    'GET',
    {"fields":"posts{created_time,likes,comments,picture,full_picture,shares,message},name,picture","access_token":this.state.disPageTken},

    function(response) {
      console.log(response)
      if (response.posts) {
        let listData = [];
        for (let i = 0; i < response.posts.data.length; i++) {
            listData.push({//code})
            }

          this.setState({ listposts: listData });
        } else {
          console.log(response.error);
        }
      }.bind(this)
          );
}
<DirectoryTree showIcon
                defaultSelectedKeys={['0']}
                switcherIcon={<Icon type="down" />} multiple defaultExpandAll onSelect={this.onSelect} onExpand={this.onExpand}>

                <TreeNode icon={<Icon type="facebook" />} title="Facebook" key="0-0" >
                  <TreeNode key="0" icon={({ selected }) => <Icon type={selected ? 'facebook' : 'frown-o'} />} title="Test Page1" key="0" isLeaf/>
                  <TreeNode
                    icon={({ selected }) => <Icon type={selected ? 'facebook' : 'frown-o'} />}
                    title="Test Page2"
                    key="1"
                    isLeaf
                  />
                </TreeNode>
              </DirectoryTree>

我不明白为什么,我尝试了componentDidMount,但我认为某些东西无法检测到变化?

1 个答案:

答案 0 :(得分:2)

这里有几件事。

您的状态没有改变,因为您调用setState的函数的this值与您期望的值不同。如果检查控制台,应该看到错误消息,表明this.setState不是函数。您需要更改以下内容:

window.FB.api('/me', 'GET', {"fields":"posts{created_time,likes,comments,picture,full_picture,shares,message},name,picture","access_token":this.state.disPageTken},
function(response) {
  console.log(response)

对此:

window.FB.api('/me', 'GET', {"fields":"posts{created_time,likes,comments,picture,full_picture,shares,message},name,picture","access_token":this.state.disPageTken},
(response) => {
  console.log(response)

箭头函数捕获this的当前值,因此该代码将按预期工作。

其次,请勿使用componentWillMount()产生副作用(例如获取)-理想情况下,根本不要使用它。在安装组件时,可能会多次调用它,这将导致多次提取。它在较新版本的React中不存在(已重命名为UNSAFE_componentWillMount())will be removed in a future version of React

请使用componentDidMount()。安装组件后,它只会被调用一次。

相关问题