I have seen this before but I still am stuck. My code where I fetch the data is as follows:
async componentDidMount(){
try {
const res = await
fetch('https://templates.accordproject.org/template-library.json');
const data = await res.json();
this.setState({
contracts: data,
});
} catch(e) {
console.log(e);
}
}
I call it here:
{this.state.contracts.map(contract => <Contract key={contract.id} contract={contract} />)}
I can see that state is:
contracts:
{
"acceptance-of-delivery@0.0.3": {
"name": "acceptance-of-delivery",
"description": "This clause allows the receiver of goods to inspect them for a given time period after delivery.",
"version": "0.0.3",
"ciceroVersion": "^0.3.0",
"type": 1
}, /// etcv for long string of json
I get the following error:
TypeError: this.state.contracts.map is not a function
I am fairly certain that map expects an array but this isn't one. My question is:
If this is the problem how do I make this.state.contracts an Array so that map will work?
map() is an array method. You can use
Object.keys(this.state.contracts).map(key=>({[key]:this.state.contracts[key]}))
This will convert the object into an array of each contract.
Or, in the above example you can try:
Object.keys(this.state.contracts).map(key=>(<Contract key={this.state.contracts[key].id} contract={this.state.contracts[key]} />))
MDN Object.keys - Detailed on Mozilla Dev.
Also, Object.values() and Object.entries() may help.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.