Tạo Store, Tạo State, Truyền Action (Cách Dùng hàm, constant, ruducer) P3

// file App.js
import React, { Component } from 'react';
import Demo from './components/Demo';
class App extends Component {
  render() {
    return (
      <div className="App">
      </div>
    );
  }
}
export default App;
// actions/index.js
import * as types from './../constants/ActionTypes';
export const status = () => {
	return {
		type: types.TOOGLE_STATUS
	}
}
export const sort = (sort) => {
	return {
		type: types.SORT,
		sort
	}
}
// file components/demo.js
import { createStore } from 'redux';
import {sort, status} from './actions/index';
import myReducer from './reducers/index';
const store = createStore(myReducer);
console.log('Default',store.getState()); 
store.dispatch(status());
store.dispatch(sort({
	by: 'name',
	value: -1
}));
console.log('SORT',store.getState());
// File constants/ActionTypes.js
export const TOOGLE_STATUS = 'TOOGLE_STATUS';
export const SORT = 'SORT';
// File constants/ActionTypes.js
export const TOOGLE_STATUS = 'TOOGLE_STATUS';
export const SORT = 'SORT';
// file reducers/index.js
import Status from './status';
import Sort from './sort';
import {combineReducers} from 'redux';
const myReducer = combineReducers({
	Status,
	Sort
});
export default myReducer;
// file reducers/sort.js
var initialState = {
	by: 'sort',
	value: 1
}
var Sort = (state = initialState, action) => {
	if(action.type === 'SORT') {
		var { by, value } = action.sort;
		return {
			by,
			value
		}
	}
	return state;
}
export default Sort;
// file reducers/status.js
var initialState = false;
var Status = (state = initialState, action) => {
	if(action.type === 'TOOGLE_STATUS') {
		state = !state;
	}
	return state;
}
export default Status;

Last updated

Was this helpful?