react redux中如何獲取store數(shù)據(jù)并將數(shù)據(jù)渲染出來
前景提要
如果不了解基礎(chǔ)的話 ----- 點(diǎn)擊此處
本文著重實(shí)現(xiàn)效果,不會講太多原理問題
未使用 react-redux 管理工具

1.創(chuàng)建倉庫骨架并書寫初始代碼
src 目錄下創(chuàng)建

//store/index.js 代碼
import { createStore } from 'redux';
import reducer from "./reducer"
const store = createStore(reducer);
export default store
//store/reducer.js
const reducer = (prevState,action)=>{
let newState = {...prevState}
return newState
}
export default reducer
2.正式開始
關(guān)鍵點(diǎn)在于 reducer.js 文件
它是一個純函數(shù),在不修改原始值的情況下返回一個新的數(shù)據(jù)
現(xiàn)在我們返回一個新的數(shù)據(jù)給 store(倉庫)
//store/reducer.js
let state = {
todos:[
{
id:1,
title:"今天周一",
isFinished:false
},
{
id:2,
title:"今天周二",
isFinished:true
}
]
}
const reducer = (prevState = state,action)=>{
let newState = {...prevState}
return newState //將新的數(shù)據(jù)返回出去
}
export default reducer
因?yàn)椴]有數(shù)據(jù)傳遞過來,所以我們用一個默認(rèn)的數(shù)據(jù)來代替,然后把它給一個新的數(shù)據(jù)再傳出去(store會自動接收return 的數(shù)據(jù))
3.store 數(shù)據(jù)獲取方法(可略過)
既然前文已經(jīng)返回?cái)?shù)據(jù),那我們就看看返回來的數(shù)據(jù)的樣子
//在任意頁面(view)引入該store
import store from './store'
console.log("store====",store)
效果圖:

這是 該 store 的方法
通過 getState()方法來獲取數(shù)據(jù)
import store from './store' console.log(store.getState())

4.數(shù)據(jù)的獲取與展示
上文中 通過 store.getState()獲取到了參數(shù),那么我們就可以把獲取到的參數(shù)賦值給現(xiàn)在的 組件的 state
import React, { Component } from 'react'
import store from '../store' //引入
export default class One extends Component {
constructor(){
super()
this.state = {
todos:[] //一定要定義一個初始值
}
}
componentDidMount(){
this.setState({
todos:store.getState().todos //將獲取到的數(shù)據(jù)里面的內(nèi)容賦值給 該頁面 state
//頁面初次渲染的時(shí)候什么都沒有,在這里獲取并修改數(shù)據(jù)
//使得頁面重新渲染,拿到數(shù)據(jù)
})
}
render() {
return (
<div>
{
this.state.todos.map(item=>{ //這里就是展示了
return(
<ul key={item.id}>
<li>{item.id}</li>
<li>{item.title}</li>
</ul>
)
})}
</div>
)
}
}
效果圖:

以上為個人經(jīng)驗(yàn),希望能給大家一個參考,也希望大家多多支持腳本之家。
相關(guān)文章
React native ListView 增加頂部下拉刷新和底下點(diǎn)擊刷新示例
這篇文章主要介紹了React native ListView 增加頂部下拉刷新和底下點(diǎn)擊刷新示例,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2018-04-04
利用React-router+Webpack快速構(gòu)建react程序
目前 React、Webpack 等技術(shù)如火如荼,你是不是還在愁苦如何把這些雜亂的知識怎么學(xué)習(xí)一下,開啟一段新的前端開發(fā)之路呢?那么這篇將給大家運(yùn)用示例代碼詳細(xì)的介紹使用React-router和Webpack如何快速構(gòu)建一個react程序,感興趣的朋友們下面來一起看看吧。2016-10-10
React路由中的redux和redux知識點(diǎn)拓展
這篇文章主要介紹了React路由中的redux和redux知識點(diǎn)拓展,文章圍繞主題展開詳細(xì)的內(nèi)容介紹,具有一定的參考價(jià)值,感興趣的朋友可以參考學(xué)習(xí)一下2022-08-08
React-View-UI組件庫封裝Loading加載中源碼
這篇文章主要介紹了React-View-UI組件庫封裝Loading加載樣式,主要包括組件介紹,組件源碼及組件測試源碼,本文給大家介紹的非常詳細(xì),對大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2022-06-06
react自定義實(shí)現(xiàn)狀態(tài)管理詳解
這篇文章主要為大家詳細(xì)介紹了react如何自定義實(shí)現(xiàn)狀態(tài)管理,文中的示例代碼講解詳細(xì),具有一定的借鑒價(jià)值,感興趣的小伙伴可以跟隨小編一起學(xué)習(xí)一下2024-01-01

