1: データ共有の手順
- Person コンポーネントを定義し、redux を通じて Count コンポーネントとデータを共有する
- 人物コンポーネントの書き込み: リデューサー、アクション、定数の構成
- キーポイント: 人のリデューサーとカウントのリデューサーは、combineReducers を使用して組み合わせる必要があります。
- メインの減速機はストアに渡します 最後に、コンポーネント内の状態を取り出すときは、「所定の位置に取り出す」ことを忘れないでください
2: たとえば、count コンポーネントと person コンポーネントの間でのデータ共有
まず、元のコンポーネントに基づいて人物コンポーネントを定義し、リデューサー、アクション、および定数を設定する必要があります。
ボタンをクリックして、人物コンポーネント ページに人物の情報を追加します。
src---->constant.js
/*
该模块是用于定义action对象中type类型的常量值,目的只有一个,便于管理的同时,防止出现拼写错误的情况
*/
export const INCREMENT='increment'
export const DECREMENT='decrement'
export const ADD_PERSON='add_person'
src----->redux----->reducers----->person.js
import {
ADD_PERSON} from '../constant'
// 初始化人的列表
const initState=[{
name:'xiaoxiao',age:18,id:'001'}]
export default function personReducer(preState=initState,action){
const {
type,data}=action
switch(type){
case ADD_PERSON://若是添加一个人
return [data,...preState]
default:
return preState
}
}
src----redux-store.js (countReducer と PersonReducer を統合)
/*
该文件专门用于暴露一个store对象,整个应用只有一个store对象
*/
// 引入createStore,专门用于创建redux最为核心的store对象
import {
legacy_createStore as createStore,applyMiddleware,combineReducers} from 'redux'
// 引入为count服务的reducer
import countReducer from './reducers/count'
// 引入为Person服务的reducer
import personReducer from './reducers/person'
// 引入redux-thunk,用于支持异步action
import thunk from 'redux-thunk'
// 汇总所有的reducer
const allReducer=combineReducers({
countReducer,
personReducer
})
// 暴露store
export default createStore(allReducer,applyMiddleware(thunk))
src----redux----アクション---->person.jsx
import {
ADD_PERSON} from '../constant'
// 创建增加一个人的action动作对象
export const createAddPersonAction=personObj=>({
type:ADD_PERSON,data:personObj})
src---->コンテナ--->人物----index.jsx
import React, {
Component } from 'react'
import {
nanoid} from 'nanoid'
import {
connect, Connect } from 'react-redux'
import {
createAddPersonAction} from '../../redux/actions/person'
class Person extends Component {
addPerson=()=>{
const name=this.nameNode.value
const age=this.ageNode.value
const personObj={
id:nanoid(),name,age}
console.log(personObj)
this.props.jiaYiRen(personObj)
this.nameNode.value=''
this.ageNode.value=''
}
render() {
return (
<div>
<h2>我是Person组件,上方组件求和为{
this.props.he}</h2>
<input ref={
c=>this.nameNode=c} type="text" placeholder='输入名字'/>
<input ref={
c=>this.ageNode=c} type="text" placeholder='输入年龄'/>
<button onClick={
this.addPerson}>添加</button>
<ul>
{
this.props.yiduiren.map((p)=>{
return <li key={
p.id}>{
p.name}----{
p.age}</li>
})
}
</ul>
</div>
)
}
}
export default connect(
state=>({
yiduiren:state.personReducer,he:state.countReducer}),//映射状态
{
jiaYiRen:createAddPersonAction}//操作映射状态的方法
)(Person)