我是新来的人,我又被困住了。我正在尝试映射数组以在子组件内部创建对象的新数组。这是我的问题-我的方法componentDidMount在数据来自父项道具之前就已执行,并且我的状态保持为空。当我在console.loging this.props和componentDidMount的末尾时,我收到一个空数组,但是当我在console.loging上的render方法时,它给了我4个空数组,然后填充到预期的300。我做错了吗?
父组件:
import "./App.css";
import { CompanyList } from "./components/companylist/companylist.component";
import { Searchfield } from "./components/searchfield/searchfield.component";
class App extends Component {
constructor(props) {
super(props);
this.state = {
companies: [],
searchfield: "",
};
}
componentDidMount = () => {
const URL = "https://xxxxx/companies";
fetch(URL)
.then((response) => response.json())
.then((data) => this.setState({ companies: data }))
.catch((error) => {
console.error("Error", error);
});
};
render() {
const filteredCompanies = this.state.companies.filter((item) =>
item.name.toLowerCase().includes(this.state.searchfield.toLowerCase())
);
return (
<div>
<Searchfield
handleChange={(e) => this.setState({ searchfield: e.target.value })}
/>
<CompanyList companies={filteredCompanies} />
</div>
);
}
}
export default App;
儿童部分:
import React, { Component } from "react";
import { Company } from "../company/company.component";
export class CompanyList extends Component {
constructor(props) {
super(props);
this.state = {
newArray: [],
};
}
componentDidMount = () => {
const filledArray = this.props.companies.map((item) => {
let result;
fetch(`https://xxxxx/incomes/${item.id}`)
.then((response) => response.json())
.then((data) => {
let transactionsToFloat = data.incomes.map((item) =>
parseFloat(item.value)
);
result = transactionsToFloat.reduce((acc, num) => {
return acc + num;
}, 0);
result = Math.round(result * 100) / 100;
});
return {
id: item.id,
name: item.name,
city: item.city,
totalIncome: result,
};
});
this.setState({ newArray: filledArray });
console.log(this.props);
};
render() {
console.log(this.props);
return (
<div>
<table>
<thead>
<tr>
<th> Id </th>
<th> Name </th>
<th> City </th>
<th> Total income </th>
</tr>
</thead>
{this.props.companies.map((item) => (
<Company key={item.id} company={item} />
))}
</table>
</div>
);
}
}
答案 0 :(得分:1)
componentWillMount()发生在render()之前。 componentDidMount()之后发生。
之所以发生这种情况,是因为React从根本上是如何工作的。 React应该感觉很快,流畅且活泼。应用程序永远都不应使用http请求或异步代码进行登录。答案是使用生命周期方法来控制DOM。
安装组件意味着什么?
更好地了解一些React词汇可能会有所帮助。安装组件后,会将其插入DOM。这是在调用构造函数时。 componentWillMount是构造函数的同义词,大约在同一时间调用。在第一次渲染后,componentDidMount只会被调用一次。
componentWillMount->渲染-> componentDidMount