React ES6类转换不工作
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
};
我一直得到错误警告:失败的上下文类型:所需的上下文router
没有在Homepage
中指定。
当我点击按钮导航时,我得到以下额外的错误Uncaught TypeError: Cannot read property transitionTo
of undefined
我甚至尝试在构造函数中添加以下内容,但无济于事
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)} />;
}
}
相关文章:
- 转换成ES 5使用babel通过吞咽手表不工作
- d3.js条形图转换无法正常工作
- d3.select()在转换后不会立即工作
- Jquery/CS3转换链接只能部分工作
- 使用 Babel 将 ES6 模块转换为 ES5 AMD 模块,无法按预期工作
- JQuery图像滑块和CSS转换只能工作一次
- css转换在for循环javascript中无法正常工作
- CSS-转换在JavaScript for循环中不能正常工作
- IE中的转换无法正常工作
- 检测Bootstrap Switch Jquery中的类更改(将工作复选框JS转换为按钮JS)
- 最大高度转换不;不工作,工作缓慢
- CSS转换don't工作(高度和边距)
- D3.js转换未按预期工作
- JavaScript for-loop:如何让我的数字转换器工作
- 从控制台中的工作函数转换为工作脚本.(请参阅编辑)
- 将 Jquery 转换为角度或使 Jquery 以角度工作
- JQuery 函数突然停止工作,转换 Javascript 参数时出错
- 将日期转换为长格式,它是如何工作的
- 如何将javascript数组转换为在IE中工作的Uint8ClampedArray
- Slim中的onclick事件不工作-转换', # x27