我的 TranslationDetail 组件在打开时传递一个 id,并基于此在类构造函数中触发外部 api 调用,将数据接收到状态,并将此数据显示在 TranslationDetail 上。
//Routing:
<Route path="/translation/:id" component={TranslationDetail}/>
//Class:
class TranslationDetail extends Component {
constructor(props){
super(props);
this.props.fetchTrans(this.props.params.id);
}
如果我手动输入网址,这一切都很好。如果我想使用 react-router 例如显示 url 下面的下一个项目确实会改变,但不会触发 api 调用,并且数据将保持不变。
<button
type="button"
onClick={() =>
browserHistory.push(`/translation/${Number(this.props.params.id)+1}`)}>
Next
</button>
请记住,我是一个完全的初学者。发生这种情况的原因是我相信构造函数只运行一次,因此不会触发进一步的 api 调用。
我该如何解决这个问题?我是否需要列出props并在更改时调用函数?如果是,如何?