我如何在上一个/后退上保存状态(数据)按钮在ReactJS中单击

时间:2018-11-29 18:39:47

标签: javascript reactjs ant-design-pro

我是reactjs的新手,我正在使用向导表单,我想保存用户数据。例如,当用户在其字段中输入数据并单击下一个按钮时(如果用户单击上一个按钮来编辑数据),我希望不会丢失用户数据。我对reactjs知之甚少。请你帮助我好吗?我还将分享我的向导表单代码,在其中我可以控制另外4个步骤

代码

import React from 'react';
import 'antd/dist/antd.css';
import './WizarStyle.css';
import styled from 'styled-components';
import { Steps, Form, Button, Card } from 'antd';
import RegisterStepOne from '../RegisterStepOne/RegisterStepOne';
import RegisterStepTwo from '../RegisterStepTwo/RegisterStepTwo';
import RegisterStepThree from '../RegisterStepThree/RegisterStepThree';
import RegisterStepFour from '../RegisterStepFour/RegisterStepFour';
import Success from '../Successful/Success';
const Step = Steps.Step;
const GeneralText = styled.div`
  color: red;
  font-size: 26px;
  font-weight: 600;
  text-align: center;
  padding-bottom: 30px;
  font-family: Lato;
  margin-top: 50px;
  color: #012653;
`;
const ButtonWrapper = styled.div`
  text-align: center;
  margin-top: 26px;
`;
class Wizard extends React.Component {
  constructor(props) {
    super(props);
    // this.modifier = null;
    this.state = {
      current: 0,
      // user: null,
    };
  }

  steps = [
    {
      title: 'General Information',
      content: (
        <RegisterStepOne
          getFieldDecorator={this.props.form.getFieldDecorator}
        />
      ),
    },
    {
      title: 'Upload Photo',
      content: (
        <RegisterStepTwo
          getFieldDecorator={this.props.form.getFieldDecorator}
        />
      ),
    },
    {
      title: 'Upload Resume',
      content: (
        <RegisterStepThree
          getFieldDecorator={this.props.form.getFieldDecorator}
        />
      ),
    },
    {
      title: 'Add Skills',
      content: (
        <RegisterStepFour
          getFieldDecorator={this.props.form.getFieldDecorator}
        />
      ),
    },
  ];

  next() {
    this.setState(prevState => ({ current: prevState.current + 1 }));
  }

  handlechanges=input=>e=>{
    this.setState({[input]:e.target.value})
  }
  handleSubmit = e => {
    e.preventDefault();
    this.props.form.validateFieldsAndScroll((err, values) => {
      if (!err) {
        // this.setState({ user: [this.state.user, values] });
        const userOject = {
          profile: {
            type: 'employee',
            screen: 'Step0',
          },
          ...values,
        };

        if (this.state.current === 0 && this.state.current <= 3) {
          fetch('http://138.197.207.41:9000/api/auth/createuser', {
            method: 'POST',
            headers: {
              Accept: 'application/json',
              'Content-Type': 'application/json',
            },
            body: JSON.stringify({
              user: userOject,
            }),
          })
            .then(response => response.json())
            .then(user => {
              if (user.error) {
                console.warn(user);
              } else if (user && user.user) {
                console.warn(user);
                localStorage.setItem('user', JSON.stringify(user.user));
                const modifier = {
                  id: user.user._id,
                  type: user.user.profile.type,
                  profile: {
                    fullName: values.fullName,
                    position: values.lastPosition,
                    username: values.username,
                    location: values.lastPosition,
                    company: values.lastCompany,
                    password: values.password,
                    photo: '',
                    screen: 'Step1',
                  },
                };
                fetch(`http://138.197.207.41:9000/api/auth/user/update`, {
                  method: 'POST',
                  headers: {
                    Accept: 'application/json',
                    'Content-Type': 'application/json',
                  },
                  body: JSON.stringify({
                    id: user.user._id,
                    modifier,
                  }),
                })
                  .then(response => response.json())
                  .then(res => {
                    if (res.error) {
                      console.warn(res);
                    } else {
                      console.warn(res);
                      this.next();
                    }
                  })
                  .done();
              }
            });
        } else {
          const user = JSON.parse(localStorage.getItem('user'));
          fetch(`http://138.197.207.41:9000/api/auth/user/updateskills`, {
            method: 'POST',
            headers: {
              Accept: 'application/json',
              'Content-Type': 'application/json',
            },
            body: JSON.stringify({
              id: user._id,
              type: user.profile.type,
              modifier: {
                'profile.skills': values.skills,
              },
            }),
          })
            .then(response => response.json())
            .then(res => {
              if (res.error) {
                console.warn(res);
              } else {
                console.warn(res);
                // this.afterDone();
                this.next();
              }
            })
            .done();
        }
      }
    });
  };

  // afterDone() {
  //   <Success getFieldDecorator={this.props.form.getFieldDecorator} />;
  // }

  prev() {
    this.setState(prevState => ({ current: prevState.current - 1 }));
  }

  getStep = props => this.steps[this.state.current].content;

  render() {
    if (this.state.current <= 3) {
      const { current } = this.state;
      const { getFieldDecorator } = this.props.form;
      return (
        <Card style={{ borderRadius: 10 }}>
          <Form onSubmit={this.handleSubmit}>
            <GeneralText>{this.steps[current].title}</GeneralText>
            <Steps current={current}>
              {this.steps.map((item, index) => (
                <Step key={index.toString()} small="small" />
              ))}
            </Steps>
            <div className="steps-content">
              {this.getStep(getFieldDecorator)}
            </div>
            <div className="steps-action">
              {' '}
              <ButtonWrapper>
                {current < this.steps.length - 1 && (
                  <Button
                    type="primary"
                    htmlType="submit"
                    style={{
                      background: '#ff9700',
                      fontWeight: 'bold',
                      border: 'none',
                    }}
                  >
                    Next
                  </Button>
                )}
                {current === this.steps.length - 1 && (
                  <Button
                    type="primary"
                    htmlType="submit"
                    style={{
                      background: '#ff9700',
                      fontWeight: 'bold',
                      border: 'none',
                    }}
                  >
                    Done
                  </Button>
                )}
                {current > 0 && (
                  <Button
                    className="preButton"
                    style={{ marginLeft: 8, border: '1px solid #ff9700' }}
                    onClick={() => this.prev()}
                  >
                    Previous
                  </Button>
                )}
              </ButtonWrapper>
            </div>
          </Form>
        </Card>
      );
    } else {
      return <Success />;
    }
  }
}
export default Form.create()(Wizard);

2 个答案:

答案 0 :(得分:0)

为此,您需要更改steps的默认行为。您可以通过使用某些CSS使用显示/隐藏功能:

.foo {
  display: none;
  opacity: 0;
  animation: fade-out 1s 1;
}
.foo.fade-in {
  display: block;
  opacity: 1;
  animation: fade-in 0.5s 1;
}

然后使用条件在js中添加/替换类:

{steps.map(({ title, content }, i) => (
      <div
        key={title}
        className={i === this.state.current ? "foo fade-in" : "foo"}
      >
        {content}
      </div>
))}

我创建了一个working demo

答案 1 :(得分:0)

看看是否不是渲染组件,您可以在本地状态下管理旧数据,如果需要,则需要将数据存储在某些商店中,例如redux,selector,

最好使用每次单击来保存当前页面数据,如果用户进入上一页,则只需获取数据表单API并将其显示为可编辑字段即可。

和我的建议使用redux存储来存储响应数据,并使用saga。它将使您成为一个聪明而又迅速的开发人员