【发布时间】:2018-07-09 07:42:16
【问题描述】:
我从后端获取文件列表并将其推送到处于组件状态的对象数组 (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
}
}
编辑:问题是当我使用条件语句渲染时,我看到控制台日志多次显示对象,这意味着它多次渲染子组件。我只想用所有必需的对象渲染一次。
【问题讨论】:
标签: javascript reactjs asynchronous promise es6-promise