reactjs 如何将props传递给子React组件?

2hh7jdfx  于 2023-05-28  发布在  React
关注(0)|答案(1)|浏览(180)

给出:
App.jsx > Welcome.js > WorkPlacePage.js
如何将props传递给WorkPlacePage.js,以便在WorkPlacePage.js中可以执行以下操作:this.props.history.push()
我现在试图传递props,但是当我console.log时,历史在控制台中被输出为undefined。

App.jsx:

import Welcome from '../containers/welcome/Welcome';

const App = ({store}) => {
  return (
    <StoreProvider store={store}>
      <ConnectedRouter history={history}>
        <Switch>
          <PrivateRoute exact path="/welcome" layout={MainLayout} component={Welcome} />
          <WithMainLayout exact path="/" component={Home} />
          <AuthRoutes path={`/${clientResourceName}`} wrapper={WithMainLayout} />
          <WithMainLayout component={NotFound} />
        </Switch>
      </ConnectedRouter>
    </StoreProvider>
  );
};

Welcome.js

import React from 'react';
import WorkPlacePage from '../../components/welcome/WorkPlacePage';

class Welcome extends React.Component {

  constructor(props) {
    super(props);
    this.state = {
      step: 1
    };
  }

  showStep() {
    const {history} = this.props

    console.log('showStep');
    console.log({history})

    switch (this.state.step) {
      case 1:
        return <WorkPlacePage history={history} />
      default:
        return (
          <div>
            <h1>Case: Default</h1>
          </div>
        );
    }
  }

  render() {
    var style = {
      width : (this.state.step / 4 * 100) + '%'
    }
    return (
      <main>
        <span className="progress-step">Step {this.state.step}</span>
        <progress className="progress" style={style}></progress>
        {this.showStep()}
      </main>
    )
  }
}

export default Welcome;

WorkPlacePage.js

import React from 'react';
import {connect} from 'react-redux';
import {bindActionCreators} from 'redux';

class WorkPlacePage extends React.Component {

  render() {

    console.log('this.props.history')
    console.log(this.props.history)

    return (
      <div>
        <h1>Workplace</h1>
        <span>
        survey things
        <button onClick={() => this.props.history.push("/confirmation")}>next page</button>
        </span>
      </div>
    );
  }
}

export default WorkPlacePage;

更新-

"react": "^15.5.4",
"react-apollo": "^1.1.2",
"react-devise": "^0.0.6",
"react-devise-material-ui": "^0.0.1",
"react-dom": "^15.5.4",
"react-redux": "^5.0.4",
"react-router-dom": "^4.1.1",
"react-router-redux": "^5.0.0-alpha.6",
yvt65v4c

yvt65v4c1#

react-router-redux导出了一个push函数。

你可以写一个动作创建器,在其中你可以像这样调用push函数:

import { push } from 'react-router-redux'

function goTo(pathname) {
    push({ pathname })
}

单击按钮时,只需分派此后藤操作。它将自己处理历史。
请记住在创建商店时添加这些行。

import { routerMiddleware } from 'react-router-redux'
import { browserHistory } from 'react-router'

const middleware = applyMiddleware(
  ...
  routerMiddleware(browserHistory),
);

const store = createStore(
  ...
  applyMiddleware(middleware)
)

希望能帮上忙。

相关问题