グローバル共有状態は、共有および送信されるだけでなく、変更可能である必要があります。1つの変更を行い、あらゆる場所で変更できます。次に、公式サイトのLieziを改良して、ステータスの共有と変更を実現します。
最初の写真:
App.js
import React,{useEffect,useReducer,useState} from 'react';
// import logo from './logo.svg';
import './App.css';
import {
// BrowserRouter as Router,
Route,
Link,
// Router
} from "react-router-dom";
import {initState,context,countReducer} from './reducer/index'
import Count from './components/Count'
import ShowCount from './components/ShowCount'
function App() {
let store=useReducer(countReducer,initState)
useEffect(()=>{
console.log('store',store)
})
let linkArr=[
{
path:'/page1',
label:'页面1'
},
{
path:'/page2',
label:'页面2'
},
{
path:'/page3',
label:'页面3'
}
]
let [currentIndex,setCurrentIndex]=useState(0)
function changeCurrentIndex(index){
setCurrentIndex(index)
}
return (
<context.Provider value={store}>
<div className="App">
<ul className="list">
{
linkArr.map((item,index)=>{
return <li className="list-item" onClick={(e)=>changeCurrentIndex(index,e)} key={index}><Link to={item.path} className={`${index===currentIndex?'active':''}`}>{item.label}</Link></li>
})
}
</ul>
<Route path='/page1' component={Page1}></Route>
<Route path='/page2' component={Page2}></Route>
<Route path='/page3' component={Page3}></Route>
</div>
</context.Provider>
);
}
function Page1(){
return (
<div>
<Count></Count>
</div>
)
}
function Page2(){
return (
<div>
<ShowCount></ShowCount>
</div>
)
}
function Page3(){
return (
<div>
this is page3
</div>
)
}
export default App;
app.jsの主な機能:トップレベルコンポーネントでcontext.Providerを使用し、唯一のストア(状態とディスパッチを含む)を以下のコンポーネントと共有します。以下のコンポーネントはいずれも、useContextを介して状態を取得し、ディスパッチします。彼らはstate.valueを共有して変更することができます。必要な状態とディスパッチを取得する方法は、useReducerを介して取得されます。
./reducer/index
import React from 'react'
let initState={
count:0
}
function countReducer(state={},action){
switch(action.type){
case 'increment':
return {count:state.count+1}
case 'decrement':
return {count:state.count-1 }
default:
return state
}
}
let context =React.createContext()
export {
countReducer,
initState,
context
}
これには、レデューサーとiniStateが含まれ、コンテキストもエクスポートされます。共有状態を使用するすべてのユーザーは、このコンテキストを使用して、すべてのコンポーネントが同じコンテキストを使用するようにする必要があります。
Count.js
import React,{useContext} from 'react'
import {context} from '../reducer/index'
function Count(){
let [state,dispatch]=useContext(context)
return (
<div>
<h1>count:{state.count}</h1>
<div>
<button style={
{width:'128px',height:'30px'}} onClick={()=>dispatch({type:'decrement'})}>-</button>
<button style={
{width:'128px',height:'30px'}} onClick={()=>dispatch({type:'increment'})}>+</button>
</div>
</div>
)
}
export default Count
count.jsの主な機能:状態を取得し、useContextを介してディスパッチして、状態を表示および変更します。
ShowCount.js
import React,{useContext} from 'react'
import {context} from '../reducer/index'
function ShowCount(){
let [state]=useContext(context)
return (
<div>
<h1>count:{state.count}</h1>
</div>
)
}
export default ShowCount
showCount.jsはcount.jsに似ています。ここでは状態のみが使用されます。