# redux-comment-manage **Repository Path**: duans/redux-comment-manage ## Basic Information - **Project Name**: redux-comment-manage - **Description**: 使用react结合redux实现的一个评论管理案例, 演示react中如何优雅的使用redux进行集中式状态管理 - **Primary Language**: Unknown - **License**: Not specified - **Default Branch**: master - **Homepage**: None - **GVP Project**: No ## Statistics - **Stars**: 0 - **Forks**: 0 - **Created**: 2019-10-24 - **Last Updated**: 2022-06-28 ## Categories & Tags **Categories**: Uncategorized **Tags**: None ## README # redux使用说明 ## redux > 状态集中管理工具, 和react配合的比较多 ### 核心方法 - `createStore(reducer)`: 创建store存储对象的方法, 需要一个`reducer()`方法作为实参 - `applyMiddleware()`: 注册redux中间件的函数 - `combineReducers()`: 合并`reducer`, 需要一个对象作为实参, 对象的成员为`reducer` - `subscribe()`: 订阅状态更新, 需要传递一个回调函数, 通过`store`来调用 ## react-redux > 连接react和redux的工具包, 可以在react中更优雅的使用redux ### 核心方法(组件) - `Provider`: 容器组件 - `connect()`高阶组件(函数), 用来将redux中管理的状态数据通过属性的方式传递给react组件 ## redux-thunk > 实现异步action的redux插件 ### 使用方法 - 导出`thunk`对象 - 在创建store对象的时候, 将`thunk`使用`applyMiddleware(thunk)`包裹后, 作为第二个参数进行传递 - `store.js` ```js import {createStore,applyMiddlware} from 'redux'; import thunk from 'react-thunk'; // 导入reducer import {reducer} from './redux/reducers' const store=createStore(reducer,applyMiddleware(thunk)); ``` ## redux-devtools-extension > redux调试工具扩展包 ### 使用 - 第1步: 通过谷歌应用商店下载安装redux调试工具插件`redux-devtools` - 第2步: 下载安装: `npm i redux-devtools-extension -D` - 第3步: 在redux代码中使用 ```jsx import {createStore,applyMiddlware} from 'redux'; import thunk from 'react-thunk'; // 导入reducer import {reducer} from './redux/reducers' // 导入composeWithDevTools函数 import {composeWithDevTools} from 'redux-devtools-extension'; // 创建store对象的时候, 调用composeWithDevTools()函数 export const store=createStore(reducers,composeWithDevTools(applyMiddleware(thunk))); ``` ## redux核心js - `store.js` ```js import {createStore} from 'redux'; // 导入redux-devtools-extension import {composeWithDevTools} from 'redux-devtools-extension'; // 导入注册中间的方法applyMidleware() import {applyMiddleware} from 'redux'; // 导入redux-thunk; 支持异步action import thunk from 'redux-thunk'; // 导入reduces import reducers from './reducers'; export const store=createStore(reducers,composeWithDevTools(applyMiddleware(thunk))); ``` - `reducers.js` ```js import {combineReducers} from 'redux'; import { ADD_COMMENT,DEL_COMMENT,QUERY_COMMENT } from './action-types'; // commentList的reducer处理函数; state必须有默认值 function commentList(state=[],action){ switch(action.type){ case ADD_COMMENT: //action.data为一个评论对象 return [action.data].concat(state); break; case DEL_COMMENT: // action.data为评论id return state.filter((item,index)=>item.id!=action.data); break; case QUERY_COMMENT: // action.data为评论列表数组 return action.data; break; // 必须声明default; 并且必须返回state; 初始化的时候会执行default分支 default: return state; } } // 合并导出reducer export default combineReducers({ commentList }) ``` - `actions.js` ```js // 创建action对象的creator工厂函数 //导入action-types import {ADD_COMMENT,DEL_COMMENT,QUERY_COMMENT} from './action-types'; // addcomment发表评论;comment评论对象 export const addComment=(comment)=>({type:ADD_COMMENT,data:comment}); // delComment删除评论;index:评论索引号 export const delComment=(index)=>({type:DEL_COMMENT,data:index}); export const getCmtList=(comments)=>({type:QUERY_COMMENT,data:comments}); // 异步action: 获取默认评论列表 export const getCmtListAsync=()=>{ return (dispatch)=>{ setTimeout(() => { const comments=[ { id:1, content:'人生若只如初见, 又何须伤感别离', author:'duans', posttime:new Date('2019/03/08').toLocaleDateString() }, { id:2, content:'若一切都已云烟成雨, 我能否变成淤泥,再一次沾染你?', author:'duans', posttime:new Date().toLocaleDateString() }, { id:4, content:'我多想再见你一面, 哪怕匆匆一眼就别离', author:'duans', posttime:new Date().toLocaleDateString() }, { id:3, content:'我多想再见你一面, 至少玩笑话还说得起', author:'duans', posttime:new Date('2019/09/18').toLocaleDateString() } ] // 通过异步的方式分发一个同步aciton dispatch(getCmtList(comments)) }, 1000); } } ``` - `action-types.js` ```js export const ADD_COMMENT='ADD_COMMENT'; export const DEL_COMMENT="DEL_COMMENT"; export const QUERY_COMMENT="QUERY_COMMENT"; ``` - 容器组件 ```jsx // 容器组件一定要导入react // import React from 'react'; // 导入connect高阶组件 import { connect } from 'react-redux'; // 导入actions import {addComment,delComment,getCmtListAsync} from '../redux/actions'; // 导入评论组件 import CmtList from '../components/CmtList'; export default connect( (state)=>({commentList:state.commentList}), {addComment,delComment,getCmtListAsync} )(CmtList) ``` - UI组件: `CmtList.jsx` ```jsx import React from 'react'; // 导入发布评论组件 import CmtPost from './CmtPost'; // 导入评论组件 import CmtItem from './CmtItem'; // prop-types import PropTypes from 'prop-types'; export default class CmtList extends React.Component { static defaultProps={ commentList:PropTypes.array.isRequired, addComment:PropTypes.func.isRequired, delComment:PropTypes.func.isRequired, getCmtListAsync:PropTypes.func.isRequired } constructor(props) { super(props); this.state = { } } componentWillMount(){ // 调用异步action,请求默认列表 this.props.getCmtListAsync(); } render() { return

评论管理-redux版


{/* 发布评论组件 */}
} } ``` - `CmtPost.jsx` ```jsx import React from 'react'; export default class CmtPost extends React.Component { constructor(props) { super(props); this.state = { } } render() { return
this.state.input=input} type="text" className="form-control" placeholder="评论人" />
} // 发表评论 addComment(){ const comment={ id:Date.now().toString().substr(10,3), author:this.state.input.value, content:this.state.textarea.value, posttime:new Date().toLocaleDateString() } if(comment.author.trim()==''){ alert('请输入评论人'); return false; } if(comment.content.trim()==''){ alert('请输入评论内容'); return false; } // 这里的调用的addComment()是redux提供的addComment(action) this.props.addComment(comment); // 重置表单 this.state.input.value=''; this.state.textarea.value=''; } } ``` - `CmtItem.jsx` ```jsx import React from 'react'; export default class CmtItem extends React.Component { constructor(props) { super(props); this.state = { } } render() { return
  • {this.props.content}

    评论人:{this.props.author}

    评论时间:{this.props.posttime}

  • } // 删除评论 delComment(id){ console.log(id,'id'); this.props.delComment(id); } } ``` --- This project was bootstrapped with [Create React App](https://github.com/facebook/create-react-app). ## Available Scripts In the project directory, you can run: ### `yarn start` Runs the app in the development mode.
    Open [http://localhost:3000](http://localhost:3000) to view it in the browser. The page will reload if you make edits.
    You will also see any lint errors in the console. ### `yarn test` Launches the test runner in the interactive watch mode.
    See the section about [running tests](https://facebook.github.io/create-react-app/docs/running-tests) for more information. ### `yarn build` Builds the app for production to the `build` folder.
    It correctly bundles React in production mode and optimizes the build for the best performance. The build is minified and the filenames include the hashes.
    Your app is ready to be deployed! See the section about [deployment](https://facebook.github.io/create-react-app/docs/deployment) for more information. ### `yarn eject` **Note: this is a one-way operation. Once you `eject`, you can’t go back!** If you aren’t satisfied with the build tool and configuration choices, you can `eject` at any time. This command will remove the single build dependency from your project. Instead, it will copy all the configuration files and the transitive dependencies (Webpack, Babel, ESLint, etc) right into your project so you have full control over them. All of the commands except `eject` will still work, but they will point to the copied scripts so you can tweak them. At this point you’re on your own. You don’t have to ever use `eject`. The curated feature set is suitable for small and middle deployments, and you shouldn’t feel obligated to use this feature. However we understand that this tool wouldn’t be useful if you couldn’t customize it when you are ready for it. ## Learn More You can learn more in the [Create React App documentation](https://facebook.github.io/create-react-app/docs/getting-started). To learn React, check out the [React documentation](https://reactjs.org/). ### Code Splitting This section has moved here: https://facebook.github.io/create-react-app/docs/code-splitting ### Analyzing the Bundle Size This section has moved here: https://facebook.github.io/create-react-app/docs/analyzing-the-bundle-size ### Making a Progressive Web App This section has moved here: https://facebook.github.io/create-react-app/docs/making-a-progressive-web-app ### Advanced Configuration This section has moved here: https://facebook.github.io/create-react-app/docs/advanced-configuration ### Deployment This section has moved here: https://facebook.github.io/create-react-app/docs/deployment ### `yarn build` fails to minify This section has moved here: https://facebook.github.io/create-react-app/docs/troubleshooting#npm-run-build-fails-to-minify