門戶網(wǎng)站系統(tǒng)設(shè)計(jì)sem全稱
react-redux
React Redux 是 Redux 的官方 React UI 綁定庫。它使得你的 React 組件能夠從 Redux store 中讀取到數(shù)據(jù),并且你可以通過dispatch
actions
去更新 store 中的 state
安裝
npm install --save react-redux
Provider
React Redux 包含一個(gè) <Provider />
組件,這使得 Redux store 能夠在應(yīng)用的其他地方使用
改造 index.js
頁面,引入Provider
import { Provider } from 'react-redux'
import store from './store'
通過 Provider
組件將 store
放在了全局的組件可以夠得到的地方
<Provider store={store} ><TotoList /></Provider>
connect
connect
方法會幫助我們訂閱store
,當(dāng)store
中的狀態(tài)發(fā)生更改的時(shí)候,會幫助我們重新渲染組件connect
方法會讓我們獲取store
中的狀態(tài),將狀態(tài)通過組件的props
屬性映射給組件connect
方法可以讓我們獲取dispatch
方法
引入connect
import { connect } from 'react-redux'
connect
有兩個(gè)值,一個(gè)是 mapStateToProps
,用于將 state
的數(shù)據(jù)通過 props
屬性映射給組件
const mapStateToProps = state => ({list: state.list
})
一個(gè)是 mapDispatchToProps
,讓我們獲取 dispatch
方法,可以將方法映射組件
const mapDispatchToProps = dispatch => ({handleChangeList(list) {dispatch({type: 'changeList',value: list})}
})
最后指定要映射的組件
connect(mapStateToProps, mapDispatchToProps)(TotoList);
這樣我們就能在組件 TotoList
使用屬性和方法了
完整代碼
import React, { useRef, useState, startTransition } from 'react';
import { connect } from 'react-redux'const TotoList = ({ list, handleChangeList }) => {const inputRef = useRef()const [value, setValue] = useState('')const items = list.map((item, index) => {return (<div key={index}><p>{item}<span onClick={() => handledel(index)}> 刪除</span></p></div>)})const handleChange = () => {startTransition(() => {setValue(inputRef.current.value)})}const handleAdd = () => {let newList = [...list]newList.push(inputRef.current.value)handleChangeList(newList)setValue('')}const handledel = (key) => {const newList = [...list]newList.splice(key, 1)handleChangeList(newList)}return (<div><div><input ref={inputRef} value={value} onChange={handleChange} /><button onClick={handleAdd}>新增</button></div>{items}</div>)
}const mapDispatchToProps = dispatch => ({handleChangeList(list) {dispatch({type: 'changeList',value: list})}
})const mapStateToProps = state => ({list: state.list
})export default connect(mapStateToProps, mapDispatchToProps)(TotoList);