Javascript 每次渲染时刷新组件状态
我有一个API正在运行,我正在尝试获取该API以获取有关某些产品的信息。我正在使用react路由器来路由产品,并使用它来获取API。然而,当我尝试点击另一个产品时,无论我做什么,来自上一个产品的信息都会保留下来 这是我的回执:Javascript 每次渲染时刷新组件状态,javascript,django,reactjs,react-router,fetch,Javascript,Django,Reactjs,React Router,Fetch,我有一个API正在运行,我正在尝试获取该API以获取有关某些产品的信息。我正在使用react路由器来路由产品,并使用它来获取API。然而,当我尝试点击另一个产品时,无论我做什么,来自上一个产品的信息都会保留下来 这是我的回执: componentWillMount(){ let id = this.props.params.id + 3; let url = 'http://localhost:8000/api/item/' + id + '/'; return fetch(url) .th
componentWillMount(){
let id = this.props.params.id + 3;
let url = 'http://localhost:8000/api/item/' + id + '/';
return fetch(url)
.then(results => results.json())
.then(results => this.setState({'items': results}))
.catch(() => console.log(this.state.items));
我在哪里打电话来填写信息
render() {
return (
<div className="itemPageWrapper">
<div className="itemImgWrapper" />
<div className="itemInfoWrapper">
<Link className="backLink" to="/">
<span className="small">
<svg fill="#000000" height="13" viewBox="0 0 18 15" width="13" xmlns="http://www.w3.org/2000/svg">
<path d="M7 10l5 5 5-5z"/>
<path d="M0 0h24v24H0z" fill="none"/>
</svg>
</span>All Items
</Link>
<h3 className="itemName">{this.state.items[Number(this.state.id)].name}</h3>
<p className="itemCost frm">{this.state.items[Number(this.state.id)].price}</p>
<p className="description">
{this.state.items[Number(this.state.id)].description}
</p>
<p className="seller frm">By <span>{this.state.items[Number(this.state.id)].brand}</span></p>
<button className="reqTradeBtn normalBtn">Order</button>
</div>
</div>
render(){
返回(
所有项目
{this.state.items[Number(this.state.id)].name}
{this.state.items[Number(this.state.id)].price}
{this.state.items[Number(this.state.id)].description}
由{this.state.items[Number(this.state.id)].brand}
命令
我收到一个错误,提示TypeError:如果我更改了任何内容,则无法读取undefined的属性'name'。我使用的是+2,因为我的API从3开始。我如何使所有产品都能使用该属性您应该检查是否已加载该项 this.state.items[编号(this.state.id)]
render(){
const item=this.state.items[编号(this.state.id)];
如果(!项){
返回“加载”;
}
返回(
......
);
}
此外,您还可以每次重写state.items。也许您应该使用一些Redux全局存储此集合。
componentWillMount
不推荐使用componentDidMount
然后小心地在render
和/或componentDidMount
中更新状态,这可能意味着额外的重新呈现和性能不足
render() {
const item = this.state.items[Number(this.state.id)];
if (!item) {
return 'Loading';
}
return (
<div className="itemPageWrapper">
......
</div>
);
}