redux 使用笔记

参考资料 阮一峰redux教程

Redux 入门教程(一):基本用法 http://www.ruanyifeng.com/blog/2016/09/redux_tutorial_part_one_basic_usages.html

Redux 入门教程(二):中间件与异步操作http://www.ruanyifeng.com/blog/2016/09/redux_tutorial_part_two_async_operations.html

Redux 入门教程(三):React-Redux 的用法http://www.ruanyifeng.com/blog/2016/09/redux_tutorial_part_three_react-redux.html

使用流程

载入依赖

npm install redux react-redux redux-thunk

<Provide>

组件在根组件外面包裹一层,其中的组件全都可以拿到state

<Provider store={store}>

       <div className="App">

         <PostForm />

         <Post />

       </div>

</Provider>

创建store.js

createStore()的三个参数:reducer,state最初的状态,applyMiddleware中间件

export const store = createStore(rootReducer,initialState,applyMiddleware(...middleware));

创建reducers文件夹,其中包括rootReducer和部分Reducer

rootReducer为index.js,用来组合所有的Reducer

export default combineReducers({

  posts:postReducer,

})

reducer 的作用:接收当前的state和action,返回新的state

export default function(state=initialState,action){

   switch(action.type){

       default:

       return state;

   }

}

创建actions文件夹和相应actions.js

在组件中引入连接connect

connect方法接受两个参数:mapStateToProps和mapDispatchToProps。它们定义了 UI 组件的业务逻辑。前者负责输入逻辑,即将state映射到 UI 组件的参数(props),后者负责输出逻辑,即将用户对 UI 组件的操作映射成 Action

export default connect(null,{fetchPosts})(Post);

在actions文件夹中新建types.js

里面定义不同的action.type

export const FETCH_POSTS = 'FETCH_POSTS'

postActions.js中引入type

通过dispatch向reducer传递action

export function fetchPosts(){

   return function (dispatch){

       fetch("https://jsonplaceholder.typicode.com/posts/")

       .then(res=>res.json())

       .then(posts=>

           dispatch({

               type:FETCH_POSTS

           }))

   }

}

在postReducer.js接收action.type

export default function(state=initialState,action){

   switch(action.type){

       case FETCH_POSTS:

       return {

           ...state

       }

       default:

       return state;

   }

}  

在post.js中定义mapStateToProps

mapStateToProps是一个函数。它的作用就是像它的名字那样,建立一个从(外部的)state对象到(UI 组件的)props对象的映射关系。

const mapStateToProps = state =>({

  posts:state.posts.items

})

©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容