随着react-router我可以使用Link元素创建的原生处理反应路由器链接.
我看到内部调用this.context.transitionTo(...).
我想进行导航,但不是从链接,例如下拉选择.我怎么能在代码中这样做?什么是this.context?
我看到了Navigationmixin,但是我可以不用mixin吗?
在当前版本的React Router(v3)中,我可以接受服务器响应并使用它browserHistory.push来转到相应的响应页面.但是,这在v4中不可用,我不确定处理它的适当方法是什么.
在此示例中,使用Redux,在用户提交表单时调用components/app-product-form.jsthis.props.addProduct(props).当服务器返回成功时,用户将进入购物车页面.
// actions/index.js
export function addProduct(props) {
return dispatch =>
axios.post(`${ROOT_URL}/cart`, props, config)
.then(response => {
dispatch({ type: types.AUTH_USER });
localStorage.setItem('token', response.data.token);
browserHistory.push('/cart'); // no longer in React Router V4
});
}
Run Code Online (Sandbox Code Playgroud)
如何从React Router v4的功能重定向到Cart页面?
我试图在 n 秒后自动更改路径。(不使用<Link to="/home">Home</Link>)。
我的代码如下所示:
class ComponentName extends Component {
constructor (props, context) {
super(props, context);
}
componentDidMount () {
setTimeout(function(){
this.context.router.transitionTo('/home');
}.bind(this), 3000)
}
render() {return (<div>..will go to the home page</div>)}
}
ComponentName.contextTypes = {
router: function () {
return React.PropTypes.func.isRequired;
}
};
export default ComponentName;
Run Code Online (Sandbox Code Playgroud)
这是我得到的错误
Uncaught TypeError: Cannot read property 'transitionTo' of undefined
在线this.context.router.transitionTo('/home');又名 this.context.router 是未定义的。
this.context 已定义,因此没有问题。
我尝试了以下一些方法:
this.context = context;
Run Code Online (Sandbox Code Playgroud)
static contextTypes: {
history: React.PropTypes.object,
location: …Run Code Online (Sandbox Code Playgroud) 我已经根据这篇文章实现了 createBrowserHisotry如何在 react-router v4 上获取历史记录?,但是它只有在我将配置属性设置为 forceRefresh: true 时才会重定向。如果我不设置任何配置属性,则 url 将更改为推送的 url,但页面不会重定向。为什么?
import React from "react";
import ReactDOM from "react-dom";
import "./index.css";
import App from "./components/App";
import { Router } from 'react-router-dom'
import registerServiceWorker from "./registerServiceWorker";
import history from "./components/common/History";
ReactDOM.render(<Router history={history}><App /></Router>,
document.getElementById('root'));
registerServiceWorker();
Run Code Online (Sandbox Code Playgroud)
import createBrowserHistory from 'history/createBrowserHistory';
// export default createBrowserHistory(); --> This redirects the ### ### URL
// but does not physically redirect
export default createBrowserHistory({
//pass a configuration object here if needed
forceRefresh: …Run Code Online (Sandbox Code Playgroud) 我如何设置 Django urls.py 和 React 组件来建立这个?我的要求是让 Django 使用 urls 文件渲染主页,如下所示:
urlpatterns = [
path('', views.index),
]
Run Code Online (Sandbox Code Playgroud)
然后,React 路由器应该渲染后续链接(例如 /home、/about)