如何在组件中设置对象的状态数组?

时间:2018-07-09 07:42:16

标签: javascript reactjs asynchronous promise es6-promise

我从后端获取文件列表,并将其推送到处于组件状态的对象数组(dirloc)。目前,控制台日志为每个文件显示了dirloc的多个日志。 一旦一切都推送到目录,我想设置状态。怎么做?

    class Load extends Component {
      constructor({ props, token }) {
        super(props, token);
        this.state = {
          nodeRes: [],
          dirloc: []
        };
      }

      componentDidMount() {
        fetch("http://192.168.22.124:3000/loadit/", {
          headers: new Headers({
            authorization: `Bearer ${this.props.token}`,
            "Content-Type": "application/json"
          })
        })
          .then(response => response.json())
          .then(logit => {
            let { dirloc, nodeRes } = this.state;
            logit.map(verifypath => {
              let getpath = verifypath.substring(0, verifypath.lastIndexOf("/"));
              let dirnames = getpath
                .toString()
                .split("/")
                .pop();
              return getpath !== ""
                ? (dirloc.push({
                    getpath: getpath /* for e.g '/folder/of/files/' */,
                    dirnames: dirnames /* array of folder names */,
                    ffiles: verifypath /* full path '/folder/of/files/abc.jpg' */
                  }),
                  this.setState({ dirloc }, () => {
                    console.log(this.state.dirloc);
                  }))
                : (nodeRes.push(verifypath), this.setState({ nodeRes }));
            });
          })
          .then(getdata => this.allFetch(this.state.nodeRes));
      }

    }

    render() {
    const {  dirloc } = this.state;
    let folderView;
    for (var i = 0; i < dirloc.length; i++) {
     if (Object.entries(dirloc).length !== 0 && dirloc.constructor !== Object) {
       folderView = <Filetree fileloc={this.state.dirloc} token={this.props.token} />
    console.log(`dirs: ${dirloc[i].getpath}`)
    } else {
        folderView = null
    }
  }

编辑:问题是,当我使用条件语句进行渲染时,我看到控制台日志多次显示对象,这意味着它将多次渲染子组件。我只想对所有必需的对象进行一次渲染。

1 个答案:

答案 0 :(得分:1)

首先生成所需的值,然后最后一次调用setState。

fetch('http://192.168.22.124:3000/loadit/', {
  headers: new Headers({
    authorization: `Bearer ${this.props.token}`,
    'Content-Type': 'application/json',
  }),
})
  .then((response) => response.json())
  .then((logit) => {
    const { dirloc, nodeRes } = this.state;
    const newDirLoc = [];
    const newNodeRes = [];
    logit.forEach((verifypath) => {
      const getpath = verifypath.substring(0, verifypath.lastIndexOf('/'));
      const dirnames = getpath.toString().split('/').pop();
      getpath !== ''
        ? newDirLoc.push({
          getpath,
          dirnames,
          ffiles: verifypath,
        })
        : newNodeRes.push(verifypath);
    });
    this.setState({
      nodeRes: [...nodeRes, ...newNodeRes],
      dirloc: [...dirloc, ...newDirLoc]
    })
  });

在渲染器中,检查循环之前的条件。

render() {
  const { dirloc } = this.state;
  let folderView;
  if (dirloc.length) {
    for (let i = 0; i < dirloc.length; i++) {
      folderView = <Filetree fileloc={this.state.dirloc} token={this.props.token} />;
      console.log(`dirs: ${dirloc[i].getpath}`);
    }
  } else {
    folderView = null;
  }
}

已将Object.entries替换为简单的长度检查,因为dirloc是一个数组。