Home > Web Front-end > JS Tutorial > body text

Share a React practice project

零下一度
Release: 2017-07-23 18:09:34
Original
1845 people have browsed it

Last time we talked about using React to write a home page with a header. This time we will use Redux for state management

Share a React practice project

Rudex

All state in the application is stored in a single store in the form of an object tree.
The only way to change state is to trigger an action, an object that describes what happened.
To describe how actions change the state tree, you need to write reducers.

We will next start the status management of login and registration

First create the redux folder in the src directory, the directory is as follows

digag
├── README.md
├── node_modules
├── package.json
├── .gitignore
├── public
│   └── favicon.ico
│   └── Share a React practice project.html
│   └── manifest.json
└── src
    └── components
        └── Index
            └── Header.js
            └── LoginDialog.js
            └── RegisterDialog.js
    └── containers
        └── App
            └── App.js
            └── App.css
    └── redux
        └── action
            └── users.js
        └── reducer
            └── auth.js
            └── users.js
        └── sagas
            └── api.js
            └── sagas.js
            └── selectors.js.js
            └── users.js
        └── store
            └── store.js
    └── App.test.js
    └── Share a React practice project.css
    └── Share a React practice project.js
    └── logo.svg
    └── registerServiceWorker.js
Copy after login

The code can be obtained from here

Remember to update the dependencies in package.json

Next I will start to explain the key code

  • action
    action/users.js

/*
 * action 类型
 */
export const REGISTER_USER = 'REGISTER_USER';
// 省略其他action 类型

/*
 * action 创建函数
 */
export const registerAction = (newUser) => {
  return{
    type:REGISTER_USER,
    data: newUser,
  }
};
// 省略其他 action 创建函数
Copy after login
  • reducer
    reducer/users.js

//Immutable Data 就是一旦创建,就不能再被更改的数据。
//对 Immutable 对象的任何修改或添加删除操作都会返回一个新的 Immutable 对象。
import Immutable from 'immutable';
//从 action 导入需要的 action 类型
import {REGISTER_USER, REGISTER_USER_SUCCESS, REGISTER_USER_FAILURE} from '../action/users';

// 初始化状态
const initialState = Immutable.fromJS({
  newUser: null,
  error: null,
  saveSuccess: false,
});

//  reducer 就是一个纯函数,接收旧的 state 和 action,返回新的 state。
export const users = (state = initialState, action = {}) => {
  switch (action.type) { // 判断 action 类型
    case REGISTER_USER:  
      return state.merge({   // 更新状态
        'newUser': action.data,
        'saveSuccess': false,
        'error': null,
      });
    case REGISTER_USER_SUCCESS:
      return state.set('saveSuccess', action.data);
    case REGISTER_USER_FAILURE:
      return state.set('error', action.data);
    default:
      return state
  }
};
Copy after login
  • store
    store/store.js

import {createStore, combineReducers, applyMiddleware } from 'redux';
import createSagaMiddleware from 'redux-saga'
import * as reducer from '../reducer/users';

import rootSaga from '../sagas/sagas';

const sagaMiddleware = createSagaMiddleware();

const store = createStore(
  combineReducers(reducer),
  applyMiddleware(sagaMiddleware)
);

sagaMiddleware.run(rootSaga);

export default store;
Copy after login

Then use store

## in the entry file #src/Share a React practice project.js

import {Provider} from 'react-redux';
import store from './redux/store/store';
// 省略其他

ReactDOM.render(
  <provider>
    <app></app>
  </provider>, document.getElementById('root')
);
Copy after login
Get action and status in App.js

import {registerAction, loginAction} from '../../redux/action/users';
import {connect} from "react-redux";
import {bindActionCreators} from "redux";
 //省略其他

class App extends Component {

  render(){
    return(
      <div>
        //省略
      </div>
    )
  }

}

export default connect(
  (state) => {
// 获取状态   state.users  是指 reducer/users.js 文件中导出的 users
// 可以 `console.log(state);` 查看状态树
  return { users: state.users }
},
  (dispatch) => {
  return {
// 创建action
    registerActions: bindActionCreators(registerAction, dispatch),
    loginActions: bindActionCreators(loginAction, dispatch),
  }
})(App);
// 在App 组件的props里就有 this.props.users  this.props.registerActions this.props.loginActions 了
// 需要注意的是这里this.props.users是Immutable 对象,取值需要用this.props.users.get('newUser') 
// 也可在 reducer 里改用 js 普通对象
Copy after login

Decorator version:

Need to enable the decorator in Babel
Decorator plug-in
babel-plugin-transform-decorators-legacy

@connect(
  (state) => {
    console.log(state);
    return ({
      users: state.users,
    });
  },
  {registerActions: registerAction, loginActions: loginAction}
)
Copy after login
Finally pass

registerActions to the RegisterDialog subcomponent,

src/components/Index/RegisterDialog. js

// 省略其他代码
 handleSubmit = (e) => {
    e.preventDefault();
    // 验证表单数据
    this.refs.user.validate((valid) => {
      if (valid) {
        // this.state.user 为表单收集的 用户注册数据
        this.props.registerActions(this.state.user);
        this.setState({loading: true});
      }
    });
  };
Copy after login
The process is:

  • Call action


    this.props.registerActions(this.state.user); The returned action is

{
    type:REGISTER_USER,
    data: this.state.user,
}
Copy after login
  • reducer updates the status according to the action type

switch (action.type) {
    case REGISTER_USER:
      return state.merge({
        'newUser': action.data,
        'saveSuccess': false,
        'error': null,
      });
//省略其他代码
Copy after login
The status in our store at this time

newUser is updated to the data collected in the registration pop-up window. It is still a synchronous action here, and registration is an asynchronous operation.

The above is the detailed content of Share a React practice project. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template