我在路由/ journal /:id上有页面,然后我想从api中获取带有' id'的数据。我将fetch添加到componentDidMount但是如果我已经在路由/ journal /:id的页面上并且从该页面使用到其他/ journal /:id,那么页面就不会改变。
似乎存在其他方式来做到这一点。请帮忙。
这是代码:
//router page
<Route component={ListLayout}>
<Route path="/journals" component={Journals} />
<Route path="/journal/:id" component={Journal} />
<Route path="/shelves" component={Shelves} />
</Route>
export default class Journal extends Component {
state = {
reader: false,
journal: {}
}
componentWillMount(){
const myHeaders = new Headers();
myHeaders.append('X-User-Agent', '84e6f2c45955b65b');
const myInit = { method: 'GET',
headers: myHeaders//,
//mode: 'cors',
//cache: 'default'
};
const myRequest = new Request(`/issues/${this.props.location.pathname.split('/').pop()}`,
myInit);
fetch(myRequest)
.then(response => {
return response.json();
})
.then(data => {
console.log(data);
this.setState({journal: data.data});
})
.catch( console.log );
}
render() {
let { journal } = this.state;
<div className="JournalPage__Title">{journal.magazine_title}</div>
<div className="JournalPage__Description">{journal.description}</div>
<Link to="/journal/432">Test fetch</Link>
}
}
答案 0 :(得分:0)
当您只更改参数时,组件不会再次加载,但是它已经收到了新的道具,因此您需要在执行参数检查后再次从componentWillReceiveProps调用API。我会将代码重构为类似的内容。
P.S。您可以使用this.props.location.params
直接获取路径参数。如果您正在使用react-router v4,请参阅此答案,了解如何从路径中获取参数
Get path params in react-router v4
export default class Journal extends Component {
state = {
reader: false,
journal: {}
}
componentWillMount(){
APIRequest(this.props.location.params);
}
componentWillReceiveProps(nextProps){
const {params: nextParams} = nextProps.location;
const {params} = this.props.location;
if(params.id !== nextParams.id) {
APIRequest(nextParams.id);
}
}
APIRequest = (id) => {
const myHeaders = new Headers();
myHeaders.append('X-User-Agent', '84e6f2c45955b65b');
const myInit = { method: 'GET',
headers: myHeaders//,
//mode: 'cors',
//cache: 'default'
};
const myRequest = new Request(`/issues/${id}`,
myInit);
fetch(myRequest)
.then(response => {
return response.json();
})
.then(data => {
console.log(data);
this.setState({journal: data.data});
})
.catch( console.log );
}
render() {
let { journal } = this.state;
<div className="JournalPage__Title">{journal.magazine_title}</div>
<div className="JournalPage__Description">{journal.description}</div>
<Link to="/journal/432">Test fetch</Link>
}
}