新建一個store文件夾,新建
state.js/reducer.js/store.js/action.js文件
state.js用來存放全局狀態值,store.js用來創建全局狀態對象並和執行相關操作的reducer.js相關聯,在
store.js中引入createStore創建對象的方法:import {createStore} from 'react',然后引入reducer.js文件,接着創建全局對象

actions.js文件中存放修改全局狀態值的數據,需要引入store.js文件中的全局狀態對象,然后引用其中的dispatch方法將修改的內容傳遞給reducer修改,

其中,type需要按照規定書寫,其中的內容可以更改,其他的內容亦可更改
reducer.js文件中執行由actions中傳遞過來的方法,並按照type的值來執行對應的方法
import state from './state'
export default(prevState=state,actions)=>{
let newDate = prevState
let {type,payload} = actions
switch (type) {
case 'ADD':
newDate.list.unshift({msg:payload,status:false})
break;
default:
break;
}
return newDate
}
需要將type和payload等數據解構出來,由於是個函數所以需要將修改后的數據返回,
在其他需要使用全局狀態值的組件頁面中,可以通過引入store對象,然后通過
store.getState()來獲取由reducer.js處理過后的數據,(如果reducer.js函數中沒有return修改后的數據,那么store.getState() 將獲取不到數據)
最后在引用全局狀態值的組件中,通過componentDidMount()生命周期使用重新渲染的方法來使頁面更新,必要時考慮性能優化,即,如果數據一樣則不渲染
componentDidMount(){
Store.subscribe(()=>{
this.setState({})
})
}
this.setState({})中放空對象的原因是使其觸發狀態值更新