WEB__frontend--React5(Redux)

2020-03-20  本文已影响0人  33jubi

Recap

review

react stateful component

Event list

async/await

A special syntax to work with promise in a more comfortable fashion

Redux+React

  1. Single source of truth
  2. State is read-only (UI-action-redux-redux store-UI)
  3. Changes are made with pure functions

项目练习

npx create-react-app redux
npm install redux react-redux
(npm install --save redux
npm install --save react-redux)

action文件夹
--index.js

export * from "./user";

--user.js

export function changeUserName({ userName }) {
    return {
        type: "CHANGE_USER_NAME", //compulsory key!
        userName
    };
}

reducers文件夹
--index.js

import { combineReducers } from "redux";
import user from "./user";

export default combineReducers({
    user
});

--user.js
···
export const user = (state = {}, action) => {
switch (action.type) {
case "CHANGE_USER_NAME":
return {
...state,
username:action.userName
}
default:
return state;
}
};
export default user;
···
..
index,js

import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import * as serviceWorker from './serviceWorker';


import { Provider } from 'react-redux';
import { createStore } from 'redux';
import rootReducer from './reducers';
let initialStore = {
};
const store = createStore(rootReducer, initialStore);
ReactDOM.render(
<Provider store={store}>
<App />
</Provider>,
document.getElementById('root'));


// If you want your app to work offline and load faster, you can change
// unregister() to register() below. Note this comes with some pitfalls.
// Learn more about service workers: https://bit.ly/CRA-PWA
serviceWorker.unregister();

app.js

import React from 'react';
import logo from './logo.svg';
import './App.css';

import {connect} from 'react-redux'
import {changeUserName} from './actions'


class App extends React.Component {
  changeUserName = () => {
    this.props.changeUserName({
    userName: "Mao Zedong"
    });
  };
  render() {
    return (
      <div>
         Hi! {this.props.userName}
        <button onClick={this.changeUserName}>Click to change username</button>
      </div>
    );
    }
  }
function mapStateToProps(state) {
    const { user } = state;
    return {
      userName: user.userName,
      status: user.status
    };
}
export default connect(
    mapStateToProps,
    { changeUserName }
)(App);
上一篇 下一篇

猜你喜欢

热点阅读