反应导航-无法读取未定义的属性“推”

时间:2020-06-25 17:45:49

标签: javascript reactjs navigation

我有一个创建个人资料页面和一个身份验证页面(其中输入了由文本发送的代码)。创建个人资料后,我想导航到身份验证页面。

我有一个用于创建个人资料页面的组件和一个用于身份验证页面的组件。

基于示例here

相关代码:

// CreateProfileComponent.js

import React from 'react';
..
import { withRouter } from "react-router";

class CreateProfile extends React.Component {

    constructor(props) {
        super(props);
    }

    handleCreateProfile(e) {
        e.preventDefault();

        if (condition) {
            createProfile(...);
            this.props.history.push('/auth');
        } else {
            // re-render
        }
    }

    render() {
        return (
            // data-testid="create-profile" - workaround (https://kula.blog/posts/test_on_submit_in_react_testing_library/) for
            // https://github.com/jsdom/jsdom/issues/1937
            <form onSubmit={this.handleCreateProfile.bind(this)} data-testid="create-profile">
                ...
            </form>
        );
    }
}

export default withRouter(CreateProfile);

// index.js
import React from 'react';
import ReactDOM from 'react-dom';
import { BrowserRouter as Router, Route } from 'react-router-dom';
import CreateProfile from './CreateProfileComponent';
import { TokenEntry } from './TokenEntryComponent';

ReactDOM.render(
  <Router>
    <ProtectedRoute exact path="/" component={ActivityList} />
    <Route path="/login" component={CreateProfile.WrappedComponent} />
    <Route path="/auth" component={TokenEntry} />
  </Router>,
  document.getElementById('root')
);

//createprofilecomponent.test.js
import React from 'react';
import { 
    LocationProvider, 
    createMemorySource,
    createHistory
} from '@reach/router';
import { render, screen, fireEvent } from '@testing-library/react';
import CreateProfile from '../CreateProfileComponent';

const source = createMemorySource('/login');
const history = createHistory(source);

let displayName = null;
let phoneNumber = null;
let legalAgreement = null;

global.window = { location: { pathname: null } };

function Wrapper({children}) {
    return <LocationProvider history={history}>{children}</LocationProvider>;
}
beforeEach(() => {
    render(
        <CreateProfile.WrappedComponent location={'/'} />, 
        { wrapper: Wrapper }
    );
});

it("navigates to /auth when good data entered", () => {
    // setup

    fireEvent.submit(screen.getByTestId('create-profile'));

    expect(global.window.location.pathname).toEqual('/auth');
});

我要

TypeError: Cannot read property 'push' of undefined

在测试期间和在Chrome中

我想念什么?

2 个答案:

答案 0 :(得分:0)

使用react-router-dom

import { withRouter } from "react-router-dom";

答案 1 :(得分:0)

已更改

export default withRouter(CreateProfile);

收件人

export const CreateProfileWithRouter = withRouter(CreateProfile);

已更改

<Route path="/login" component={CreateProfileWithRouter.WrappedComponent} />

收件人

<Route path="/login" component={CreateProfileWithRouter} />

Pull request created,将一个示例包含在withRouter的文档中。

示例gist