试图让withRouter与我的Provider类一起使用

时间:2019-04-16 14:47:17

标签: reactjs

使用上下文API在React中进行注册路由(用于后端的Mongodb已经设置并且运行良好)。登录成功后,我要重定向URL。在我尝试使用withRouter设置导出以使用this.props.history之前,它一直运行良好。

provider类可以正常工作,但是以这种方式导出this.props.history时未定义:

export class Provider extends Component {

当我尝试使用下面的代码将其导出时,它会引发错误-有关错误,请参见下文

提供程序类

import React, { Component } from 'react';
import axios from 'axios';
import {withRouter} from 'react-router';

const AuthContext = React.createContext();

class Provider extends Component {

  state = {
    firstName: null,
    lastName:null,
    emailAddress: null,
    password: null,
    signedIn: false,
  };

  logOut = () => {
    this.setState({ 
      firstName: null,
      signedIn: false
    });
  };

  userData = (event) => {
    this.setState({
      [event.target.name]: event.target.value
    });
  };

  logIn = (event) => {
    event.preventDefault();
    axios.get(`http://localhost:5000/api/users`, {
      auth: {
        username: this.state.emailAddress,
        password: this.state.password
      }
    }).then(res => {
      this.setState({
        firstName: res.data.firstName,
        signedIn: true
      })
      this.props.history.push("/");
      console.log('successful')
    }).catch(err => {
      console.log('unsuccessful')
      console.log(err)
    });
  }

  render(){
    return (
      <AuthContext.Provider value = {{
        firstName: this.state.firstName,
        signedIn: this.state.signedIn,
        actions: {
          signedIn: this.state.signedIn,
          logIn: this.logIn,
          logOut: this.logOut,
          userData: this.userData
        }
      }}>
        {this.props.children}
      </AuthContext.Provider>

    )
  }
}
export default withRouter(Provider)
export const Consumer = AuthContext.Consumer

APP.JS

export default class App extends Component {
  render() {
    return (
      <BrowserRouter>
      <Provider>
          <Header />
          <Switch>
            <Route exact path='/courses' render={() =>  <Redirect to='/' />}/>   
            <Route exact path='/' component={Courses} />
            <Route path='/courses/create' component={CreateCourse} />
            <Route exact path='/courses/:id' component={CourseDetail} />
            <Route path='/courses/:id/update' component={UpdateCourse} />
            <Route path='/signin' component={UserSignIn} />
            <Route path='/signup' component={UserSignUp} />
            <Route component = {PageNotFound} />
          </Switch>
      </Provider>
      </BrowserRouter>
    );
  };
};

这是我在上面的代码中看到的浏览器错误: Attempted import error: 'Provider' is not exported from './Components/Context'

如果我删除export default withRouter(Provider)并用此行export class Provider extends Component导出,它将正常工作!但我需要以某种方式访问​​this.props.history。

是否有任何重定向网址的建议?或如何使用withRouter正确导出我的提供程序类?非常感谢

0 个答案:

没有答案