簡單理解Redux

以前我一直使用的是dva,說實話,感受dva比redux更優秀簡單(畢竟是redux的改進版)。可是最近有接觸的項目要是用redux,在之前看了一下redux,但沒太理解就去學習了dva。關於redux的學習文檔,感受初學者看一遍可能會有點懵。我也不太喜歡閱讀文字,因此本篇文章大部分都是代碼,例子是基於官網的例子,我稍做了一些修改,只要你會react,相信一下就能理解redux。react

1.入口文件,和中文文檔的同樣。

import React from 'react'
import { render } from 'react-dom'
import { Provider } from 'react-redux'
import { createStore } from 'redux'
import todoApp from './reducers'
import App from './components/App'

let store = createStore(todoApp)

render(
  <Provider store={store}>
    <App />
  </Provider>,
  document.getElementById('root')
)

 

2.action ,其實action就像一個指令,命令某人作某事,但它須要被派遣(dispatch)

let nextTodoId = 0
export const addTodo = text => {
//必需返回一個對象,並且含有type屬性
  return {
    type: 'ADD_TODO',
    id: nextTodoId++,
    text
  }
}

export const setVisibilityFilter = filter => {
  return {
    type: 'SET_VISIBILITY_FILTER',
    filter
  }
}

export const toggleTodo = id => {
  return {
    type: 'TOGGLE_TODO',
    id
  }
}

 

3.reducers,裏面會描述真正的作事的過程,每個reducer的名字就是store(整個應用的state)的一個屬性名。

index.jsredux

import { combineReducers } from 'redux'
import todos from './todos'
import visibilityFilter from './visibilityFilter'

const todoApp = combineReducers({
  todos,
  visibilityFilter
})

export default todoApp

 

todos.jsdom

const todos=(state=[],action)=>{
  switch(action.type){
    case 'ADD_TODO':
      return [
        ...state,
        {
          id:action.id,
          text:action.text,
          completed:false
        }
      ]

    case 'TOGGLE_TODO':
      return state.map(todo=>
          (todo.id===action.id)
          ?{...todo,completed:!todo.completed}
          :todo
        )
    default:
      return state
  }
}
export default todos

 
visibilityFilter.jside

const visibilityFilter = (state = 'SHOW_ALL', action) => {
  switch (action.type) {
    case 'SET_VISIBILITY_FILTER':
      return action.filter
    default:
      return state
  }
}

export default visibilityFilter

 

4.components,就是頁面的組件,三部分組成

App.js學習

import Footer from './Footer'
import React from 'react'
import AddTodo from './AddTodo'
import MyTodoList from '../components/MyTodoList'

const App = () => (
  <div>
    <AddTodo />
    <MyTodoList />
    <Footer />
  </div>
)

export default App

 
AddTodo.jsui

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

class AddTodo extends React.Component {
  constructor(props){
    super(props);
    this.state={
      val:''
    }
  }

  handleSubmit=()=>{
    const {val}=this.state
    if(val.trim()){
      this.props.dispatch(addTodo(val))
      this.setState({val:''})
    }
  }
  handleChange=(e)=>{
    this.setState({val:e.target.value})
  }

  render() {
    const {dispatch}=this.props;
    const { val } =this.state;

    return (
      <div>
        <input  onChange={this.handleChange} value={val} />
        <button onClick={ this.handleSubmit}>add</button>
      </div>
    )
  }
}

//通過connect這個HOC包裹的組件,props裏面自帶dispatch屬性
export default connect()(AddTodo)

 
MyTodoList this

import React from 'react'
import { connect } from 'react-redux';
import { toggleTodo } from '../actions';


class MyTodoList extends React.Component{
  state={

  }
  handleChange=(id)=>{
    this.props.dispatch(toggleTodo(id))
  }


  render(){
    const {todos}=this.props;
    return(
      <ul>
        {todos.map((todo,index)=>(<li key={index} style={{textDecoration:todo.completed?'line-through':'none'}} onClick={()=>this.handleChange(index)}>{todo.text}</li>))}
      </ul>
    )
  }
}

const mapStateToProps=state=>{
  console.log(state)
//這裏進行todo的狀態篩選,完成點擊按鈕顯示不一樣狀態的todo的功能
  switch(state.visibilityFilter){
    case('SHOW_ACTIVE'):
      return {todos:state.todos.filter(item=>!item.completed)}
    case('SHOW_COMPLETED'):
      return {todos:state.todos.filter(item=>item.completed)}
    default:
      return {todos:state.todos}
  }
 
}
export default connect(mapStateToProps)(MyTodoList)

 
Footer.jsspa

import React from 'react'
import { setVisibilityFilter } from '../actions'
import { connect } from 'react-redux';


class Footer extends React.Component{

  state={
    activeButton:'all'
  }

  handleShowAll=()=>{
    this.setState({activeButton:'all'})
    this.props.dispatch(setVisibilityFilter('SHOW_ALL'))
  }
  handleShowActive=()=>{
    this.setState({activeButton:'active'})
    this.props.dispatch(setVisibilityFilter('SHOW_ACTIVE'))
  }
  handleShowCompleted=()=>{
    this.setState({activeButton:'completed'})
    this.props.dispatch(setVisibilityFilter('SHOW_COMPLETED'))
  }

  render(){
    const { activeButton}=this.state;
    return(
      <div>
        <button onClick={this.handleShowAll} style={activeButton==='all'?{background:'red'}:{background:''}}>show all</button>
        <button onClick={this.handleShowActive} style={activeButton==='active'?{background:'red'}:{background:''}}>show active</button>
        <button onClick={this.handleShowCompleted} style={activeButton==='completed'?{background:'red'}:{background:''}}>show completed</button>
      </div>
    )
  }

}

export default connect()(Footer)

 
 
 
 
 
 

代碼裏面只用到了mapStateToProps(),它的第一個參數就是整個應用的state,state裏面有哪些屬性,就看這裏code

const todoApp = combineReducers({
  todos,
  visibilityFilter
})

 
 

代碼目錄結構
代碼結構component

相關文章
相關標籤/搜索