是一個數據倉庫,一個應用中store是惟一的,它裏面封裝了state狀態,當用戶想訪問state的時候,只能經過store.getState來取得state對象。css
action描述了一個更新state的動做,它是一個對象,其中type屬性是必須有的,reducer會根據type來指定某動做和要修改的值。react
{
type: FETCH_POSTS,
payload: posts // 數據源
}
複製代碼
dispatch是一個方法,它用於派發一個action,這是惟一的可以修改state的方法。git
fetch("https://jsonplaceholder.typicode.com/posts")
.then(
posts => dispatch({
type: FETCH_POSTS,
payload: posts
})
)
複製代碼
reducer是更新state的核心,它裏面已經封裝好了更新state的邏輯,接受兩個參數,state和action,將新值更新到舊的state對象上返回。github
// 根據action的type,返回不一樣數據
switch (action.type) {
case FETCH_POSTS:
return {
...state,
items: action.payload
};
default:
return state;
}
複製代碼
屏幕快照 2019-09-02 下午2.54.02.pngjson
import { Provider } from 'react-redux';
import { store } from './redux/store';
// Provider包裹以後,全部的組件均可以拿到store庫中數據
<Provider store={store}>
// 項目中經常使用Provider包裹最底層父組件,以保證全部組件都能共享數據
<Index />
</Provider>
複製代碼
import {applyMiddleware, createStore} from "redux";
import rootReducer from './reducers/index.js';
import thunk from 'redux-thunk'; // thunk做用是異步的分發action
const middleware = [thunk]; // 中間件
const initialState = {};
複製代碼
// applyMiddleware將全部中間件組成一個數組並依次執行
export const store = createStore(
rootReducer,
initialState,
applyMiddleware(...middleware),
);
複製代碼
// 分發操做
export const fetchPosts = () => dispatch => {
fetch("https://jsonplaceholder.typicode.com/posts")
.then(res => res.json())
.then(posts => dispatch({
type: 'FETCH_POSTS', // type是必需要有的
payload: posts // 有效數據
}));
};
複製代碼
const initialState = {
items: [],
item: {}
};
// reducer接受兩個參數,第一個是state,第二個是action
export default function (state = initialState, action) {
switch (action.type) {
case FETCH_POSTS:
return {
...state,
items: action.payload
};
default:
return state;
}
}
複製代碼
import {connect} from 'react-redux';
import {fetchPosts} from "../redux/actions/postActions";
@connect(state => {
let {items, item} = state.posts;
return {
items,
item
}
},{fetchPosts})
複製代碼
componentDidMount () {
this.props.fetchPosts();
}
componentWillReceiveProps (nextProps) {
if(nextProps.item){
this.props.items.unshift(nextProps.item);
}
}
複製代碼
yarn add babel-plugin-import --save
// 在package.json中添加
"babel": {
"presets": [
"react-app"
],
"plugins": [
[
"import",
{
"libraryName": "antd",
"style": "css"
}
]
]
}
複製代碼
// 將最新的state映射到當前組件,經過mapStateToProps訂閱store
const mapStateToProps = state => ({
posts: state.posts.items,
});
// 將當前組件Posts和action進行連接
// connect接受兩個參數,第二個參數裏面能夠包含多個方法
export default connect(mapStateToProps,{fetchPosts})(Posts)
複製代碼
yarn add babel-plugin-transform-decorators-legacy
// 可省略如上步驟,在頭部引入所需state和action,而後直接導出組件
@connect(state => {
let {
items,
item
} = state.posts;
return {
items,
item
}
},{fetchPosts}),
export default Posts;
複製代碼
剛剛加入掘金社區,歡迎提出寶貴的意見,一塊兒進步學習。數組