【问题标题】:How to convert class baes component into functional component in Reactjs如何在 Reactjs 中将基于类的组件转换为功能组件
【发布时间】:2021-11-12 11:12:04
【问题描述】:

如何将此class based component 转换为functional component。因为这是一个基于类的简单组件,我想将react class based component 转换为functional componentredux hooks。我想使用redux hoooks在这个组件中。我对class based components 不满意,因为this 关键字对我来说是最令人困惑的词。我想使用来自react-redux 钩子的useSelector hookuseDispatch。在我使用条件渲染的这个组件中

import React from "react";
import { connect } from "react-redux";  
import { AUTH_ERRORS, login } from "../ducks/client";
class Login extends React.Component {
  render() {
    if (this.props.error === AUTH_ERRORS.CERTIFICATE) {
      return (
        <div className="Page">
          <h2>Connection error</h2>
        </div>
      );
    }
   
    return (
      <div className="Home Page">
        <h2>Login</h2>
        <form className="form" onSubmit={this.handleSubmit}>
          {this.props.error === AUTH_ERRORS.CREDENTIALS && (
            <h4 className="formError">Incorrect username or password</h4>
          )}
   
          <label htmlFor="jid">Username</label>
          <input
            ref={(el) => (this._jid = el)}
            type="text"
            name="jid"
            id="jid"
            placeholder="Username"
          />
          <label htmlFor="password">Password</label>
          <input
            ref={(el) => (this._password = el)}
            name="password"
            type="password"
            id="password"
            placeholder="Password"
          />
          <div className="actions">
            <input type="submit" value="Log in" />
          </div>
        </form>
      </div>
    );
  }
   
  handleSubmit = (e) => {
    e.preventDefault();
    if (this._jid.value.length && this._password.value.length) {
      this.props.login(this._jid.value, this._password.value);
    }
  };
}
   
const mapStateToProps = (state) => ({
  error: state.client.error,
});
   
export default connect(mapStateToProps, { login })(Login);

【问题讨论】:

标签: reactjs react-redux


【解决方案1】:

这是您作为功能组件的代码:

const { Provider, useDispatch, useSelector } = ReactRedux;
const { createStore, applyMiddleware, compose } = Redux;

const initialState = {
  client: { error: {} },
};
//action creators
const loginAction = (id, pwd) => ({
  type: 'LOGIN',
  payload: { id, pwd },
});
const reducer = (state, { type, payload }) => {
  console.log('in reducer', type, payload);
  return state;
};
//creating store with redux dev tools
const composeEnhancers =
  window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ || compose;
const store = createStore(
  reducer,
  initialState,
  composeEnhancers(
    applyMiddleware(
      () => (next) => (action) => next(action)
    )
  )
);
const AUTH_ERRORS = {};
function Login(props) {
  const dispatch = useDispatch();
  const _jid = React.useRef();
  const _password = React.useRef();
  const login = React.useCallback(
    (id, pwd) => dispatch(loginAction(id, pwd)),
    [dispatch]
  );
  const handleSubmit = React.useCallback(
    (e) => {
      e.preventDefault();
      if (
        _jid.current.value.length &&
        _password.current.value.length
      ) {
        login(_jid.current.value, _password.current.value);
      }
    },
    [login]
  );
  const error = useSelector((state) => state.client.error);

  if (error === AUTH_ERRORS.CERTIFICATE) {
    return (
      <div className="Page">
        <h2>Connection error</h2>
      </div>
    );
  }

  return (
    <div className="Home Page">
      <h2>Login</h2>
      <form className="form" onSubmit={handleSubmit}>
        {error === AUTH_ERRORS.CREDENTIALS && (
          <h4 className="formError">
            Incorrect username or password
          </h4>
        )}

        <label htmlFor="jid">Username</label>
        <input
          ref={_jid}
          type="text"
          name="jid"
          id="jid"
          placeholder="Username"
        />
        <label htmlFor="password">Password</label>
        <input
          ref={_password}
          name="password"
          type="password"
          id="password"
          placeholder="Password"
        />
        <div className="actions">
          <input type="submit" value="Log in" />
        </div>
      </form>
    </div>
  );
}

ReactDOM.render(
  <Provider store={store}>
    <Login />
  </Provider>,
  document.getElementById('root')
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.8.4/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.8.4/umd/react-dom.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/redux/4.0.5/redux.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-redux/7.2.0/react-redux.min.js"></script>


<div id="root"></div>

这是您other question的答案

const Members = ['John', 'Ali', 'Nagar', 'colony'];
const asName = (names) =>
  names.length === 0
    ? 'no members'
    : names.length === 1
    ? `${names[0]}`
    : names.length === 2
    ? `${names[0]},${names[1]}`
    : `${names[0]},${names[1]} +${names.length - 2}`;

console.log(asName(Members.slice(0, 0)));
console.log(asName(Members.slice(0, 1)));
console.log(asName(Members.slice(0, 2)));
console.log(asName(Members.slice(0, 3)));
console.log(asName(Members.slice(0, 4)));

【讨论】:

    猜你喜欢
    • 2020-08-26
    • 1970-01-01
    • 2021-11-27
    • 1970-01-01
    • 2020-10-27
    • 1970-01-01
    • 1970-01-01
    • 2020-10-17
    • 2021-11-24
    相关资源
    最近更新 更多