Redux Todos Example

此項目模板是使用Create React App構建的,它提供了一種簡單的方法來啟動React項目而無需構建配置。
使用Create-React-App構建的項目包括對ES6語法的支持,以及幾種非官方/尚未最終形式的Javascript語法
先看效果
1037363-20190428101130947-1442397131.gif
這個例子可以幫助你深入理解在 Redux 中 state 的更新與組件是如何共同運作的。
展示了 reducer 如何委派 action 給其它 reducer,也展示了如何使用 React Redux 從展示組件中生成容器組件。

//index.js 跟組件
import React from 'react'
import { render } from 'react-dom'
import { createStore } from 'redux'
import { Provider } from 'react-redux'
import App from './components/App'
import rootReducer from './reducers'const store = createStore(rootReducer)render(<Provider store={store}><App /></Provider>,document.getElementById('root')
)

先看action,action是對象

let nextTodoId = 0
// Action 本質上是 JavaScript 普通對象。我們約定,action 內必須使用一個字符串類型的 type 字段來表示將要執行的動作。
// 多數情況下,type 會被定義成字符串常量。當應用規模越來越大時,建議使用單獨的模塊或文件來存放 action。
export const addTodo = text => ({type: 'ADD_TODO',id: nextTodoId++,text
})export const setVisibilityFilter = filter => ({type: 'SET_VISIBILITY_FILTER',filter
})export const toggleTodo = id => ({type: 'TOGGLE_TODO',id
})export const VisibilityFilters = {SHOW_ALL: 'SHOW_ALL',SHOW_COMPLETED: 'SHOW_COMPLETED',SHOW_ACTIVE: 'SHOW_ACTIVE'
}

接下來看reducer
這個是combineReducers

import { combineReducers } from 'redux'
import todos from './todos'
import visibilityFilter from './visibilityFilter'export default combineReducers({todos,visibilityFilter
})

這個是reducer操作純函數

//純函數操作state
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.js中是進行過濾函數

import { VisibilityFilters } from '../actions'const visibilityFilter = (state = VisibilityFilters.SHOW_ALL, action) => {switch (action.type) {case 'SET_VISIBILITY_FILTER':return action.filterdefault:return state}
}export default visibilityFilter
//app.js
//這個是根APP組件
import React from 'react'
import Footer from './Footer'
import AddTodo from '../containers/AddTodo'
import VisibleTodoList from '../containers/VisibleTodoList'const App = () => (<div><AddTodo /><VisibleTodoList /><Footer /></div>
)export default App

這個是footer.js

//這是一個footer組件
import React from 'react'
import FilterLink from '../containers/FilterLink'
import { VisibilityFilters } from '../actions'const Footer = () => (<div><span>Show: </span><FilterLink filter={VisibilityFilters.SHOW_ALL}>All</FilterLink><FilterLink filter={VisibilityFilters.SHOW_ACTIVE}>Active</FilterLink><FilterLink filter={VisibilityFilters.SHOW_COMPLETED}>Completed</FilterLink></div>
)
export default Footer
//link組件
import React from 'react'
import PropTypes from 'prop-types'const Link = ({ active, children, onClick }) => (<buttononClick={onClick}disabled={active}style={{marginLeft: '4px',}}>{children}</button>
)Link.propTypes = {active: PropTypes.bool.isRequired,children: PropTypes.node.isRequired,onClick: PropTypes.func.isRequired
}export default Link
//todo組件
import React from 'react'
import PropTypes from 'prop-types'const Todo = ({ onClick, completed, text }) => (<lionClick={onClick}style={{textDecoration: completed ? 'line-through' : 'none'}}>{text}</li>
)Todo.propTypes = {onClick: PropTypes.func.isRequired,completed: PropTypes.bool.isRequired,text: PropTypes.string.isRequired
}export default Todo

這個是todoList組件

import React from 'react'
import PropTypes from 'prop-types'
import Todo from './Todo'const TodoList = ({ todos, toggleTodo }) => (<ul>{todos.map(todo =><Todokey={todo.id}{...todo}onClick={() => toggleTodo(todo.id)}/>)}</ul>
)TodoList.propTypes = {todos: PropTypes.arrayOf(PropTypes.shape({id: PropTypes.number.isRequired,completed: PropTypes.bool.isRequired,text: PropTypes.string.isRequired}).isRequired).isRequired,toggleTodo: PropTypes.func.isRequired
}export default TodoList

接下來展示了如何使用 React Redux 從展示組件中生成容器組件。
在container中的是AddTodo.js

//addtodo.js
import React from 'react'
import { connect } from 'react-redux'
import { addTodo } from '../actions'const AddTodo = ({ dispatch }) => {let inputreturn (<div><form onSubmit={e => {e.preventDefault()if (!input.value.trim()) {return}dispatch(addTodo(input.value))input.value = ''}}><input ref={node => input = node} /><button type="submit">Add Todo</button></form></div>)
}export default connect()(AddTodo)
//FilterLink.js
import { connect } from 'react-redux'
import { setVisibilityFilter } from '../actions'
import Link from '../components/Link'const mapStateToProps = (state, ownProps) => ({active: ownProps.filter === state.visibilityFilter
})const mapDispatchToProps = (dispatch, ownProps) => ({onClick: () => dispatch(setVisibilityFilter(ownProps.filter))
})export default connect(mapStateToProps,mapDispatchToProps
)(Link)
//VisibleTodoList.js
import { connect } from 'react-redux'
import { toggleTodo } from '../actions'
import TodoList from '../components/TodoList'
import { VisibilityFilters } from '../actions'const getVisibleTodos = (todos, filter) => {switch (filter) {case VisibilityFilters.SHOW_ALL:return todoscase VisibilityFilters.SHOW_COMPLETED:return todos.filter(t => t.completed)case VisibilityFilters.SHOW_ACTIVE:return todos.filter(t => !t.completed)default:throw new Error('Unknown filter: ' + filter)}
}const mapStateToProps = state => ({todos: getVisibleTodos(state.todos, state.visibilityFilter)
})const mapDispatchToProps = dispatch => ({toggleTodo: id => dispatch(toggleTodo(id))
})export default connect(mapStateToProps,mapDispatchToProps
)(TodoList)

轉載于:https://www.cnblogs.com/smart-girl/p/10782616.html

本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/news/394025.shtml
繁體地址,請注明出處:http://hk.pswp.cn/news/394025.shtml
英文地址,請注明出處:http://en.pswp.cn/news/394025.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

有效電子郵件地址大全_如何優雅有效地處理介紹電子郵件

有效電子郵件地址大全by DJ Chung由DJ Chung 如何優雅有效地處理介紹電子郵件 (How to handle intro emails gracefully and effectively) 您想幫個忙時不想忘恩負義... (You don’t want to sound ungrateful when asking for a favor…) Let me tell you the story that ins…

notability錄音定位_Notability的一些使用技巧?

作為使用了一年Notability的考研狗 今天也來回答回答這個問題&#xff0c;希望可以給考研的同學一點點幫助。這個軟件的優點估計大家都知道&#xff0c;我在這里就不多說了。好吧&#xff0c;還有一個原因是我比較懶&#xff01;好了不多說廢話了&#xff0c;等會你們要打我了本…

python實現軟件的注冊功能(機器碼+注冊碼機制)

sklearn實戰-乳腺癌細胞數據挖掘 https://study.163.com/course/introduction.htm?courseId1005269003&utm_campaigncommission&utm_sourcecp-400000000398149&utm_mediumshare 一、前言&#xff1a;目的&#xff1a;完成已有python圖像處理工具的注冊功能功能&am…

leetcode1306. 跳躍游戲 III(bfs)

這里有一個非負整數數組 arr&#xff0c;你最開始位于該數組的起始下標 start 處。當你位于下標 i 處時&#xff0c;你可以跳到 i arr[i] 或者 i - arr[i]。 請你判斷自己是否能夠跳到對應元素值為 0 的 任一 下標處。 注意&#xff0c;不管是什么情況下&#xff0c;你都無法…

Win10 UWP開發系列:使用VS2015 Update2+ionic開發第一個Cordova App

原文:Win10 UWP開發系列&#xff1a;使用VS2015 Update2ionic開發第一個Cordova App安裝VS2015 Update2的過程是非常曲折的。還好經過不懈的努力&#xff0c;終于折騰成功了。 如果開發Cordova項目的話&#xff0c;推薦大家用一下ionic這個框架&#xff0c;效果還不錯。對于Cor…

vavr_使用Vavr在Java 8流中更好的異常處理

vavrby Rajasekar Elango由Rajasekar Elango In this post, I will provide tips for better exception handling in Java 8 streams using the Functional Java library Vavr.在這篇文章中&#xff0c;我將提供使用Functional Java庫Vavr在Java 8流中更好地處理異常的技巧。 …

Python-strace命令追蹤ssh操作

Python-strace命令追蹤ssh操作 通過strace 命令追蹤ssh的進程ID&#xff0c;記錄操作的命令[實際上是內核里面記錄的東西]&#xff0c;進行操作日志的Py解析達到效果 追蹤進程并寫入ssh操作到文件中 Ps: 此時機器A已經ssh登錄了機器B&#xff0c;取得它的ssh進程PID 機器A登錄后…

java h2 derby_嵌入式H2數據庫的Spring配置以進行測試

小編典典由于我不知道是否有任何工具可以檢查數據庫&#xff0c;我認為一個簡單的解決方案是使用支持HSQL&#xff0c;H2和Derby 的Spring嵌入式數據庫(3.1.x docs&#xff0c;current docs)。 。使用H2&#xff0c;你的xml配置如下所示&#xff1a;如果你更喜歡基于Java的配置…

基礎的python程序_Python程序入門

Python語法元素入門Python語法元素分析注釋注釋&#xff1a;程序員在代碼中加入的說明信息&#xff0c;不被計算機執行注釋的兩種方法&#xff1a;單行注釋以#開頭多行注釋以開頭和結尾# Here are the commentsThis is a multiline commerntused in Python縮進1個縮進 &#xf…

解決阿里云服務器磁盤報警

一般磁盤報警涉及到實際磁盤和inode文件索引節點 1.df -h檢查磁盤占用不高 2.df -i檢查inode文件索引節點有一個掛載目錄達到89%,里面有一個目錄產生大量的4k大的緩存文件,刪除該目錄下的文件解決: 刪除該目錄下小于4kb的文件 find /data/tmp -type f -size -4 -exec rm -rf {}…

leetcode310. 最小高度樹(bfs)

對于一個具有樹特征的無向圖&#xff0c;我們可選擇任何一個節點作為根。圖因此可以成為樹&#xff0c;在所有可能的樹中&#xff0c;具有最小高度的樹被稱為最小高度樹。給出這樣的一個圖&#xff0c;寫出一個函數找到所有的最小高度樹并返回他們的根節點。格式該圖包含 n 個節…

如何構建自己的免費無服務器評論框

by Shaun Persad通過Shaun Persad 如何構建自己的免費無服務器評論框 (How you can build your own free, serverless comment box) Contentful’s flexible content modeling goes far beyond blog posts. Here’s how you can leverage Contentful and Netlify to create a …

[Swift]LeetCode1035.不相交的線 | Uncrossed Lines

★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★?微信公眾號&#xff1a;山青詠芝&#xff08;shanqingyongzhi&#xff09;?博客園地址&#xff1a;山青詠芝&#xff08;https://www.cnblogs.com/strengthen/&#xff09;?GitHub地址&a…

BZOJ1054(搜索)

大力搜&#xff0c;狀態用一個16位的數字表示。 1 #include <bits/stdc.h>2 3 using namespace std;4 5 #define rep(i,a,b) for(int i(a); i < (b); i)6 7 const int A 30 1;8 9 struct node{int x, y; } op[A]; 10 struct Nod…

php sql語句過濾,php如何做sql過濾

php如何做sql過濾SQL注入攻擊指的是通過構建特殊的輸入作為參數傳入Web應用程序&#xff0c;而這些輸入大都是SQL語法里的一些組合&#xff0c;通過執行SQL語句進而執行攻擊者所要的操作&#xff0c;其主要原因是程序沒有細致地過濾用戶輸入的數據&#xff0c;致使非法數據侵入…

ajaxfileupload 返回值_ajaxFileUpload上傳文件返回json無法解析

最近做一個文件上傳的功能&#xff0c;還要綁定數據傳輸到后臺&#xff0c;為了不影響前端的體驗&#xff0c;采用ajax發送請求。找了一些資料&#xff0c;網上的用ajaxupload這個插件。但是無論成功還是失敗都是執行的error的回調函數。后臺我采用springmvc返回的json&#xf…

leetcode133. 克隆圖(bfs)

給你無向 連通 圖中一個節點的引用&#xff0c;請你返回該圖的 深拷貝&#xff08;克隆&#xff09;。 圖中的每個節點都包含它的值 val&#xff08;int&#xff09; 和其鄰居的列表&#xff08;list[Node]&#xff09;。 class Node { public int val; public List neighbor…

OSCON上最受歡迎的Docker演講

本文講的是OSCON上最受歡迎的Docker演講&#xff0c;【編者的話】本文介紹了上個月OSCON大會有關Docker最受歡迎的一個分享&#xff1a;真實線上環境的Docker技巧。分享者是一名運維工程師叫Bridget&#xff0c;她所在的公司DramaFever在2013年10月開始在線上環境部署使用Docke…

測試驅動開發 測試前移_測試驅動開發:它是什么,什么不是。

測試驅動開發 測試前移by Andrea Koutifaris由Andrea Koutifaris Test driven development has become popular over the last few years. Many programmers have tried this technique, failed, and concluded that TDD is not worth the effort it requires.在過去的幾年中&…

【C/C++開發】C++庫大全

C特殊限定符(1)--static 當static來修飾類數據成員時&#xff0c;這個類的所有對象都可以訪問它。因為值在內存中持續存在&#xff0c;它可以被對象有效共享。這意味著當一個對象改變static數據成員的值時&#xff0c;就改變了所有對象的這個數據成員的值。 定義一個類: class …