我正在从CodePen上看到的代码中迁移代码。
在IssueBox
中,我计划实现一种表格,最终用户将更新该表格,将状态从“未验证”更改为“已验证”。
App
(将其重命名)将是我的父级,而IssueBox
将是子级。
所以我通过了磁通=>操作->调度程序-> udpate数据库->更新视图。
现在我有了新的状态并且应该更新视图,我是否要使用componentWillRecieveProps()然后在其中使用setState,以便可以在IssueBox
中继续使用this.props,从而依次更新它。 / p>
import React, { Component } from "react";
import IssueBox from "./issuebox.js";
import "./App.css";
class App extends Component {
constructor(props) {
super(props);
this.state = {
isLoaded: false,
email: [],
counter: 0,
title: "Test run"
};
}
componentDidMount() {
fetch(
"https://s3-us-west-2.amazonaws.com/s.cdpn.io/311743/dummy-emails.json"
)
.then(res => res.json())
.then(result => {
const emails = result.data;
console.log("resutl state: ", emails);
let id = 0;
for (const email of emails) {
email.id = id++;
email.verified = 'False'
}
this.setState({
isLoaded: true,
emails: emails
});
});
}
render() {
//console.log(this.state.email);
return (
<div className="App">
<div>
<IssueBox emails={this.state.email} />
</div>
</div>
);
}
}
//issuebox.js
import React, { Component } from "react";
class IssueBox extends Component {
constructor(args) {
super(args);
const emails = this.props.emails;
console.log("inner props: ", emails);
let id = 0;
for (const email of emails) {
email.id = id++;
}
this.state = {
selectedEmailId: 0,
currentSection: "inbox",
emails
};
}
// ...从密码笔复制并插入
setSidebarSection(section) {
let selectedEmailId = this.state.selectedEmailId;
if (section !== this.state.currentSection) {
selectedEmailId = "";
}
this.setState({
currentSection: section,
selectedEmailId
});
}
componentWillReceiveProps(newProps) {
// Assign unique IDs to the emails
this.setState({ emails: newProps.data });
}
render() {
const currentEmail = this.state.emails.find(
x => x.id === this.state.selectedEmailId
);
return (
<div>
<Sidebar
emails={this.props.emails}
setSidebarSection={section => {
this.setSidebarSection(section);
}}
/>
)}
///.....copy and pase from codepen
答案 0 :(得分:1)
该错误是由componentWillReceiveProps()
中的这一行引起的:
this.setState({ emails: newProps.data });
电子邮件进入名为emails
的属性,因此该行应为:
this.setState({ emails: newProps.emails });
话虽这么说,componentWillReceiveProps()
gets called more frequently than you might expect。我建议您将id
添加到componentDidMount()
的{{1}}内的电子邮件中,以便它们进入App
即可使用。这意味着IssueBox
会将电子邮件保持在其状态,只是将它们作为道具传递给App
,因此您可以从IssueBox
的状态中删除emails
,而只需使用通过IssueBox
内各处的道具传入的电子邮件(类似于其他组件使用IssueBox
进入道具的方式,而不是使其保持在本地状态)。