【发布时间】:2025-11-24 01:50:02
【问题描述】:
我有一个表单 onsubmit 它必须路由到 list.js 。 如何路由到 list.js 以在单击添加文章按钮时显示所有文章 当我收到以下错误时
TypeError: Cannot read property 'history' of undefined
ConnectedForm.handleSubmit
E:/reacr-redux/src/components/Form.js:31
28 | const id = uuidvl();
29 | this.props.addArticle({ title , id });
30 | this.setState({title:''});
> 31 | this.props.router.history.push('/List');
| ^ 32 | }
33 | render(){
34 | const {title}=this.state;
View compiled
▶ 18 stack frames were collapsed.
This screen is visible only in development. It will not appear if the app crashes in production.
Open your browser’s developer console to further inspect this error.
组件/form.js
import React ,{ Component } from 'react';
import {connect} from 'react-redux';
import uuidvl from 'uuid';
import { addArticle } from '../js/actions/index';
import PropTypes from 'prop-types';
const mapDispatchtoProps= dispatch=>{
return{
addArticle:article =>dispatch(addArticle(article))
};};
class ConnectedForm extends Component{
constructor(){
super();
this.state={
title:''
} }
static contextTypes={
router:PropTypes.object,
}
handleChange(eVal,nm){
this.setState({"title":eVal})
}
handleSubmit(ev){
ev.preventDefault();
const { title }=this.state;
const id = uuidvl();
this.props.addArticle({ title , id });
this.setState({title:''});
this.props.router.history.push('/List');
}
render(){
const {title}=this.state;
return(
<div>
<form onSubmit={this.handleSubmit.bind(this)}>
<input type='text' value={title} id="title" onChange={(e)=>this.handleChange(e.target.value,'article')}/>
<button type="submit">Add</button>
</form>
</div>
);} }
const Form =connect(null,mapDispatchtoProps)(ConnectedForm);
export default Form;
源/索引
import index from "./js/index";
import React from 'react';
import { render } from 'react-dom';
import { Provider } from 'react-redux';
import store from './js/store/index';
import App from './App';
import * as serviceWorker from './serviceWorker';
import { BrowserRouter as Router , Route , Switch } from 'react-router-dom';
import Form from './components/Form';
import List from './components/List';
import Userdashboard from './components/unimoniC/Userdashboard';
render(
<Provider store={store}>
<Router>
<Switch>
<Route exact path="/" component={App}/>
<Route path="/Form" component={Form}/>
<Route path="/List" component={List}/>
<Route path="/Userdashboard" component={Userdashboard}/>
</Switch>
</Router>
</Provider>
, document.getElementById('root'))
serviceWorker.unregister();
我应该使用 react redux 路由器,因为我正在使用 react 路由器 dom 我需要安装一些插件或withrouter吗?我不知道。 谁能让我知道我哪里出错了?
【问题讨论】:
-
你使用的是哪个版本的 react-router
-
@ShubhamKhatri m 使用 react rotuer dom ^4.3.1
-
请检查重复的帖子。它解释了你的问题
标签: reactjs redux react-redux