我正在努力构建一个多步骤表单流,用户首先加载:/welcome
,然后让用户通过以下内容
step 0: `/welcome` (Should redirect to step 1)
step 1: `/welcome/workplace`
step 2: `/welcome/profile`
这是我到目前为止所做的:
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;
作为反应,我可以使用你的建议:
/welcome
,则将浏览器自动重定向到第1步的正确方法是/welcome/workplace
=Uncaught TypeError: Cannot read property 'push' of undefined
---为什么没有定义历史记录?感谢您提供任何专家帮助!
答案 0 :(得分:1)
是的,确定这个结构看起来不错。我认为您希望为每个步骤创建一个单独的路径组件,因为我确信每个步骤都会随着更多规则和验证而增长。
要重定向,您可以呈现<Redirect to="/somewhere/else"/>
- https://github.com/ReactTraining/react-router/blob/master/packages/react-router/docs/api/Redirect.md
您需要将道具传递到<WorkPlacePage />
类似的东西:
class Welcome extends React.Component {
constructor(props) {
super(props);
this.state = {
step: 1
};
}
render() {
const {history} = this.props
switch (this.state.step) {
case 1:
return <WorkPlacePage history={history} />
case 2:
return (
<div>
<h1>WIP</h1>
</div>
);
default:
return (
<div>
<h1>Case: Default</h1>
</div>
);
}
}
}