javascript - 如何在组件中设置对象数组?

标签 javascript reactjs asynchronous promise es6-promise

我从后端获取文件列表并将其推送到组件状态下的对象数组 (dirloc)。目前控制台日志显示每个文件的多个 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
    }
  }

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

最佳答案

首先生成所需的值,然后在最后调用一次 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 是一个数组。

关于javascript - 如何在组件中设置对象数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51240354/

相关文章:

android - 异步运行一个方法

c# - 使用await顺序调用异步任务有什么好处?

javascript - 从对象数组中查找对象索引的最佳方法是什么 - javascript

javascript - 多个数组元素的组合

javascript - 仅当我更改类 Prop 时如何安装组件

javascript - 如何从异步调用返回响应?

javascript - 多个 JavaScript 按钮简化为一个函数

graph - d3.js 中的网络多路由正交图

javascript - 渲染 react 组件时出错(对象而不是字符串)

javascript - 管理员和用户面板的两个项目 VS 具有不同主题的单个应用程序