我正在使用react-router v4,我可以得到“this.props.history”。但是,“this.props.history.push(”/ Anli /“+ page)”(在Anli.js中,功能更改页面)当浏览器地址栏中的URL发生变化时,())不起作用。
但是“this.prop.history.push(”/ home“)”工作了。我不知道为什么。
感谢帮助。
index.js
import { BrowserRouter as Router, Route, Redirect, Switch} from 'react-router-dom';
import React from 'react';
import Anli from '../views/anli/Anli';
class RouterIndex extends React.Component{
render(){
return(
<Router>
<Switch>
<Route path="/home" exact component={Home}></Route>
<Route path="/AnLi/:page" render={props => <Anli {...props}/>}></Route>
<Redirect from="/*" to="/home" />
</Switch>
</Router>
);
}
}
App.js
import React, { Component } from 'react';
import 'antd/dist/antd.css';
import { createStore } from 'redux'
import { Provider } from "react-redux";
import RouterIndex from './router';
import reducer from './reducer/reducer';
const store = createStore(reducer);
class App extends Component {
render() {
return (
<Provider store={store}>
<RouterIndex/>
</Provider>
);
}
}
A努力.就是
import React from 'react'
import TopNavbar from '../../components/navbar/TopNavbar';
import SuspendBar from '../../components/suspendBar/SuspendBar';
import ajaxhost from '../../ajaxhost';
import SubCards from '../../components/subPageCard/SubCards';
import {Pagination} from "antd";
import { withRouter,Link } from "react-router-dom";
import "./anli.css"
import Footer_ from '../../components/footer/Footer_';
class Anli extends React.Component {
constructor(props) {
super(props);
this.state = {
datas: [],
pages:{}
}
this.changePage = this.changePage.bind(this);
}
componentDidMount() {
let page = this.props.match.params.page;
let url_;
if (page === 1) {
url_ = this.state.url
}else{
url_ = this.state.url + suffix + page
}
let url = encodeURIComponent(url_).replace(new RegExp("%", "g"), '~');
let that = this;
fetch(ajaxhost +'/search/hunlicehua/'+ url, {
method: 'GET'
}).then((res) => {
if (res.ok) {
res.json().then(function (result) {
debug && console.log(result);
that.setState({
datas:result.datas,
pages:result.pages
})
})
}
}).catch((res) => {
console.log(res);
})
}
changePage(page){
console.log(this.props.history);
this.props.history.push("/AnLi/"+ page);
}
render() {
const {datas,pages} = this.state;
const current = parseInt(this.props.match.params.page);
const total = parseInt(pages.list[pages.list.length - 1].num);
return (
<div history={this.props.history}>
<TopNavbar/>
<SuspendBar/>
<SubCards datas={datas}/>
<div className="pagination-custom" >
<Pagination defaultCurrent={current} total={total} onChange={this.changePage}/>
</div>
<Footer_ />
</div>
);
}
}
第一次尝试:
代替 :
changePage(page){
console.log(this.props.history);
this.props.history.push("/AnLi/"+ page);
}
确保传入一个字符串(作为参数)而不是一个整数,然后将字符串组合在一起,或者你可以运行page.toString()
第二次尝试:
而不是抽象出onClick事件并运行history.push,你可以使用react-routers Link
组件作为按钮吗?
<Link to={`/topics/${id}`}>{name}</Link>
看看这篇关于react-router的最新文章。
https://tylermcginnis.com/react-router-nested-routes/
每当我在项目中实现路径更改时,我总是使用Link
组件,您可以将更改和动态路径直接传递到to
组件的Link
道具。