首页
IT
登录
6mi
u
盘
搜
搜 索
IT
Redux入门案例todo
Redux入门案例todo
xiaoxiao
2021-03-25
155
redux入门案例写在一个页面中实现,增加数据与删除数据(官方版的简写)[忽视项目中的命名]
'use strict'
;
import
React,{Component} from
'react'
;
import
{createStore} from
"redux"
;
function
add(text) {
return
{
type
:
"ADD"
,
value
:text, } }
function
reduce(arg) {
return
{
type
:
"DE"
,
value
:arg, } }
function
todo(state=[],action){
switch
(action.type){
case
"ADD"
:
return
[...state,action.value];
case
"DE"
:
return
state.filter
((item,index)=>{
return
item != action.value; })
default
:
return
state
} } //创建
store
let
store
=
createStore
(todo)
;
export
default
class
Todo
extends
Component
{
constructor
(props)
{
super
(props)
;
this
.
state
= {
data
:[] }
this
.
add1
=
this
.
add1
.
bind
(
this
)
; }
add1
()
{
let
dom
=
this
.
refs
.
input
store
.
dispatch
(add(dom.value))
dom
.
value
= ""; }
delete
(arg)
{
store
.
dispatch
(reduce(arg))
}
componentWillMount
()
{
store
.
subscribe
(()=>{
this
.setState({ data:store.getState() }) })
}
render
()
{
return
( <div> <p> <input type=
"text"
ref=
"input"
/> <input type=
"button"
value=
"新增"
onClick={
this
.add1}/> </p> <ul> {
this
.state.data.map((item,index)=>( <li key={`
list-${index}
`}> <span>{item}</span> ------------- <a href=
"javascript:;"
onClick={
this
.
delete
.bind(
this
,item)}>x</a> </li> )) } </ul> </div> )
} }
转载请注明原文地址: https://ju.6miu.com/read-2860.html
技术
最新回复
(
0
)