[英]React ES6 Class transitionTo Not Working
內部類
constructor(props, context) {
super(props, context);
someFn = () = {
this.context.router.transitionTo('google.com');
}
在組件的底部
MyComponent.contextTypes = {
router: React.PropTypes.func.isRequired
};
我不斷收到錯誤警告:失敗的上下文類型: Homepage
中未指定所需的上下文router
。
當我單擊按鈕進行導航時,出現以下附加錯誤: 未捕獲的TypeError:無法讀取未定義的屬性transitionTo
我什至嘗試在構造函數中添加以下內容,但無濟於事
this.context = context
絕大多數應用程序不需要使用上下文。 (參考: https : //reactjs.org/docs/context.html )
下面應該可以幫助您=>
import {Component} from 'react';
import PropTypes from 'prop-types';
class MyComponent extends Component {
static contextTypes = {
router: PropTypes.object
};
onFormSubmit() {
this.context.router.push('/home');
}
render() {
return (
<form onSubmit={this.onFormSubmit.bind(this)}>
</form>
);
}
}
我在react-router github repo中問了同樣的問題並得到了答案https://github.com/rackt/react-router/issues/2107
要點: history
是舊router
替代品
class Component extends React.Component {
static contextTypes= {
history: React.PropTypes.object,
location: React.PropTypes.object
}
render() {
console.log(this.context.history, this.context.location)
return null;
}
}
我在下面嘗試並正常工作。 我的react-router
是1.0.0-rc3
。
export default class MyComponent extends React.Component {
static contextTypes = {
history: React.PropTypes.object
}
routeHandler() {
this.context.history.pushState(null, '/test');
}
render() {
return <button onClick={this.routeHandler.bind(this)} />;
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.