redux的做一些補(bǔ)充
- 安裝redux add react-redux
- provider 第一個(gè)核心api
- 在入口src文件夾中的index.js中使用,包裹其他組件
- 并在provider添加store={store}屬性,這樣它所包裹的組件就都可以使用store中的數(shù)據(jù)了
- 怎么獲取store,就要用下面這個(gè) connect api
- 第二個(gè)核心api
- 它能讓需要使用store數(shù)據(jù)的組件和store做連接
- mapStateToProps ==> 把store中的state數(shù)據(jù)映射到組件中的props里面
- mapDispatchToProps ==> 把store中的dispatch方法掛載到props上
/**
* index.js
*/
import React from 'react'
import ReactDOM from 'react-dom'
import TodoList from './todoList'
import { Provider } from './store'
const App = (
<provider store={store}>
<TodoList/>
</provider>
)
ReactDOM.render(App, documnet.getElementById('root'));
// -----------------分割線------------------------------------------------------------------------------
/**
* TodoList組件
*/
import React, { Component } from 'react';
import { connect } from 'react-redux'; // 引用react-redux這個(gè)對(duì)象中的一個(gè)屬性,要使用解構(gòu)賦值,用花括號(hào)包裹
const TodoList = (props) => {
const { inputValue, list, handleInputChange, handleClick, handleDelete } = props
render() {
return (
<div>
<div>
<input value={inputValue} onChange= {handleInputChange}/>
<button onClick={handleClick}>提交</button>
</div>
<ul>
{
this.porps.list.map((item,index)=>{
return <li onClick = {() => { handleDelete(index) }} key={index}>{item}</li>
})
}
</ul>
</div>
)
}
}
// mapStateToProps ==> 把store中的state數(shù)據(jù)映射到組件中的props里面
const mapStateToProps = (state) => {
return {
inputValue: state.inputValue,
list: state.list
}
}
// mapStateToProps ==> 把store中的state數(shù)據(jù)映射到組件中的props里面
const mapDispatchToProps = (dispatch) => {
return {
handleInputChange (e) {
const action ={
type: 'change_input_value',
value: e.target.value
}
dispatch(action)
console.log(e.target.value)
},
handleClick () {
const action ={
type: 'add_todolist_item'
}
dispatch(action)
},
handleDelete (index) {
const action = {
type: 'delete_todolist_item',
index
}
dispatch(action)
}
}
}
export default connect(mapStateToProps,mapDispatchToProps)(TodoList)
// -------------------分割線---------------------------------------------------------------------------
/**
* reducer.js
*/
const defaultState = {
inputValue: '' ,
list: []
}
export default (state= defaultState, action) => {
if( action.type === 'change_input_value') {
const newState = JSON.parse(JSON.stringify(state));
newState.inputValue = action.value;
return newState
}
if ( action.type === 'add_todolist_item') {
const newState = JSON.parse(JSON.stringify(state));
newState.list.push(newState.inputValue)
newState.inputValue = ''
return newState
}
if ( action.type === 'delete_todolist_item') {
const newState = JSON.parse(JSON.stringify(state));
newState.list.splice(action.index, 1)
return newState
}
return state
}
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。