当我在导航栏上单击具有不同ID的路径时,它不会获取与该ID相关的数据。
代码:
import React, { Component } from 'react';
import { Route, Switch } from "react-router-dom";
import { Layout } from './components/Layout';
import JobsIndex from './components/jobs/jobs_index';
import JobItems from './components/jobs/job_items';
import SupplierShow from './components/supplier/supplier_index';
import UsersIndex from './components/users/users_index';
import './custom.css'
export default class App extends Component {
static displayName = App.name;
render () {
return (
<Layout>
<Switch>
<Route path="/jobitems/:id" component={JobItems} />
<Route path="/jobs" component={JobsIndex} />
<Route path="/supplier" component={SupplierShow} />
<Route exact path="/users/:id" component={UsersIndex} />
</Switch>
</Layout>
);
}
}
当我单击“用户”选项卡时,它仅将URL更改为 https:// localhost:44312 / users / 0 ,而无需刷新数据。 Users / 0返回所有用户,而Users / 1返回特定用户。不太确定我缺少什么。
UserIndex代码:
import React, { Component } from 'react';
import { connect } from 'react-redux';
import { fetchPost } from '../../actions/users';
class UsersIndex extends Component {
componentDidMount() {
const id = this.props.match.params.id;
this.props.fetchPost(id);
this.state.id = id;
}
constructor(props) {
super(props);
this.onSubmit = this.onSubmit.bind(this);
}
state = {
visible: false,
active: true,
errors: {},
id: 0
}
答案 0 :(得分:1)
更改ID后,reaction不会删除并创建新组件。它会更新您的组件,然后调用componentdidupdate
import React, { Component } from 'react';
import { connect } from 'react-redux';
import { fetchPost } from '../../actions/users';
class UsersIndex extends Component {
componentDidMount() {
const id = this.props.match.params.id;
this.props.fetchPost(id);
this.state.id = id;
}
componentDidUpdate(prevProps) {
if(this.props.match.params.id !== prevProps.match.params.id){
const id = this.props.match.params.id;
this.props.fetchPost(id);
this.state.id = id;
}
}
constructor(props) {
super(props);
this.onSubmit = this.onSubmit.bind(this);
}
state = {
visible: false,
active: true,
errors: {},
id: 0
}