簡體   English   中英

在redux中使用重構

[英]use recompose in redux

我有一個使用react和redux開發的組件。 現在我想使用重構,我不明白有組織的方式將它與redux一起使用。 通過有條理的方式,我的意思是說在我之前有兩個函數,比如mapStateToPropsmapDispatchToProps ,它們包含在connect HOC ,這使得代碼在我看來看起來更具可讀性和mapDispatchToProps 我的問題是我如何做同樣的方式,就像我為redux部分做的那樣? 我找不到這種方式,所以我不確定是否有辦法,如果有人可以通過分享幫助我,好嗎?

這是我的代碼

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

const mapStateToProps = state => ({
  loginData: state.loginData,
});

const mapDispatchToProps = dispatch => ({
  login: user => dispatch(login(user)),
});

class Login extends React.Component<{ login: Function }> {
  state = {
    error: false,
    user: {
      email: '',
      password: '',
    },
  };

  handleChange = (e) => {
    const { name, value } = e.target;
    this.setState({ user: { ...this.state.user, [name]: value } });
  };

  handleSubmit = (e) => {
    e.preventDefault();
    this.props.login(this.state.user);
  };

  renderError() {
    if (this.state.error) {
      return (
        <ErrorMessage>
          The following email is not associated with us. Please create an
          account to use our service
        </ErrorMessage>
      );
    }
    return <div />;
  }
  render() {
    const { user } = this.state;
    return (
      <WhitePart>
        <UpperPart>
          <TitleContainer>
            <TitleText>Login</TitleText>
          </TitleContainer>
          {this.renderError()}
          <Form>
            <form onSubmit={this.handleSubmit}>
              <StyledField
                label="Email"
                id="email"
                name="email"
                type="text"
                value={user.email}
                placeholder="Email"
                className="input-field"
                component={GTextField}
                onChange={this.handleChange}
                style={{
                  marginBottom: '20px',
                }}
                required
                fullWidth
              />
              <StyledField
                label="Password"
                id="password"
                name="password"
                type="password"
                value={user.password}
                placeholder="Password"
                className="input-field"
                component={GPasswordField}
                onChange={this.handleChange}
                required
                fullWidth
              />
              <ButtonContainer>
                <PrimaryButton
                  type="submit"
                  style={{
                    textTransform: 'none',
                    fontFamily: 'Lato',
                    fontWeight: 300,
                  }}
                >
                  Login
                </PrimaryButton>
              </ButtonContainer>
            </form>
          </Form>
        </UpperPart>
      </WhitePart>
    );
  }
}

export default connect(
  mapStateToProps,
  mapDispatchToProps,
)(Login);

for handleChange和handleSubmit我可以使用withHandler和withState但是對於mapStateToProps和mapDispatchToProps我不熟悉。

直接回答你的問題:

export default compose(
  connect(
    mapStateToProps,
    mapDispatchToProps
  ),
  withStateHandlers,
  withHandler,
)(Login);

獎金! 🙂

使用recompose時,您不需要單獨的mapDispatchToProps 我們喜歡為所有處理程序使用withHandlerswithHandlers ,包括Redux調度。

看起來像這樣。

import React from 'react';
import { connect } from 'react-redux';
import { signUpUser, loginUser } from './someActionsFile';

const LandingScreen = props => (
  <ButtonContainer>
    <Button title="Sign Up" onPress={props.dispatchSignUpUser} />
    <Button title="Log In" onPress={props.dispatchLoginUser} />
    <Button title="Say Hi!!" onPress={props.sayHi} />
  </ButtonContainer>
);

const mapStateToProps = state => ({
   loginData: state.loginData,
});

const myHandlers = withHandlers({
  dispatchSignUpUser: ({ dispatch }) => () => {
    dispatch(signUpUser());
  },
  dispatchLoginUser: ({ dispatch }) => () => {
    dispatch(loginUser());
  },
  sayHi: () => () => {
    console.log('Hi!!');
  }
});

export default compose(
  connect(mapStateToProps), // Once connect() is composed `dispatch` is prop.
  myHandlers
)(LandingScreen);

對於mapStateToProps:

您可以使用reselect將選擇器邏輯移動到另一個文件中,然后跨組件共享選擇器。

對於mapDispatchToProps:

你可以使用redux-thunkredux-saga將異步邏輯移動到單獨的文件中。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM