欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

react+redux+Instagram

程序员文章站 2023-12-25 12:45:57
项目地址:https://github.com/xiaoyuqing/react-redux-instagram,喜欢的话动动手指点点赞^-^ 1.初始化项目 IndexRoute是默认路由 2.增加store文件 const history = syncHistoryWithStore(brows ......

项目地址:xiaoyuqinginstagram,喜欢的话动动手指点点赞^-^

1.初始化项目

indexroute是默认路由

react+redux+Instagram

 

 

2.增加store文件

const history = synchistorywithstore(browserhistory, store)
用synchistorywithstore是为了让react-router 的 history 跟 store 互相同步

3.增加action文件

包括增加❤️,增加评论,删除评论

4.增加reducer文件

combinereducers 把一个由多个不同 reducer 函数作为 value 的 object,合并成一个最终的 reducer 函数,然后就可以对这个 reducer 调用 createstore 方法。
为了让router与redux保持一致,要把routereducer加进来,必须是routing,不是routing会报错。

const rootreducer = combinereducers({posts, comments, routing: routerreducer });

5.把provider引进来,把store传给provider,history传给router

 <provider store={store}>
    <router history={history}>
      
    </router>
  </provider>

 

6.创建一个app组件,编写mapstatetoprops,mapdispachtoprops,用connect把组件跟store连接起来,用bindactioncreators结合actioncreators跟dispatch,把 action creator 往下传到一个组件

const app = connect(mapstatetoprops, mapdispachtoprops)(main);

 

7.接下来创建photo组件,把photo组件传给photogrid,主页已经创建好了。修改post的reducer,点❤️的时候增加like数,还有动效

//  post reducer
function posts(state = [], action) {
  switch(action.type) {
    case 'increment_likes' :
      console.log("incrementing likes!!");
      const i = action.index;
      return [
        ...state.slice(0,i), // before the one we are updating
        {...state[i], likes: state[i].likes + 1},
        ...state.slice(i + 1), // after the one we are updating
      ]
    default:
      return state;
  }
}

react+redux+Instagram

 

 

react+redux+Instagram

 


8.接下来创建comments组件,comments可以增加评论跟删除评论,在single里面引入comments跟photo,增加comments的reducer,详情页就建好了

function postcomments(state = [], action) {
  switch(action.type){
    case 'add_comment':
      // return the new state with the new comment
      return [...state,{
        user: action.author,
        text: action.comment
      }];
    case 'remove_comment':
      // we need to return the new state without the deleted comment
      return [
        // from the start to the one we want to delete
        ...state.slice(0,action.i),
        // after the deleted one, to the end
        ...state.slice(action.i + 1)
      ]
    default:
      return state;
  }
  return state;
}

 react+redux+Instagram

 

总结

一个项目做下来,对redux跟react-redux的使用更加熟悉了,发现redux对于组件间的数据管理真的是很有效果的

 

github地址xiaoyuqinginstagram, 喜欢的话动动手指点点赞^-^

 

上一篇:

下一篇: