美文网首页
React + Redux 遇到的坑

React + Redux 遇到的坑

作者: 抓住时间的尾巴吧 | 来源:发表于2017-05-02 14:20 被阅读2359次

    这两天在忙公司移动端的项目,我们采用的技术是React,配合Redux进行数据的存取,期间遇到了不少坑。

    导航切换 加载更多

    1.根据当前的列表数list.size和列表总数count来判断是否需要按钮来执行加载更多。

    1.切换category,首先获取categoryID。
    2.然后根据categoryID获取List Count,将Count存入对应的category中,同时将读取状态初始化并存入category中,后续会根据数据读取状态来判断Loading是否显示。
    3.更改category中的读取状态,显示为获取中,然后根据categoryID获取List,将List存入对应的Blog List中,再更改读取状态,表示读取成功。

    handleClickCategory(e) {
        const categoryID = parseInt(e.target.id.replace('blog_category_', ''), 10);
        if (this.props.BlogStateActiveCategoryID !== categoryID) {
          this.props.updateBlogStateActiveCategoryID(categoryID);
    
          const blogListAfterFilter = this.props.BlogStateBlogList.filter((blog) => (blog.category === categoryID));
    
          if (blogListAfterFilter.isEmpty()) {
            this.updateActiveCategoryBlogCount(categoryID);//更新count
            this.updateBlogList(categoryID);//获取List并更新
          }
        }
      }
    
    //获取count 并初始化fetch状态
    updateActiveCategoryBlogCount(categoryID) {
        const { BlogStateCategory } = this.props;
        getBlogCount(categoryID)
          .then((blogCount) => {
            this.props.updateBlogStateCategory(
              BlogStateCategory.update(
                BlogStateCategory.findIndex((categoryItem) => (categoryItem.get('id') === categoryID)),
                (categoryItem) => (categoryItem.merge({
                  count: parseInt(blogCount, 10),
                  fetchPending: true,//表示读取数据中,需要显示loading和更改button文案
                  fetchFail: false,
                  fetchSuccess: false,
                }))
              )
            );
          });
      }
    
    updateBlogList(categoryID) {
        const { BlogStateBlogList, BlogStateCategory } = this.props;
        this.props.updateBlogStateCategory(
          BlogStateCategory.update(
            BlogStateCategory.findIndex((categoryItem) => (categoryItem.get('id') === categoryID)),
            (categoryItem) => (categoryItem.merge({
              fetchPending: true,//表示读取数据中,需要显示loading和更改button文案
              fetchFail: false,
              fetchSuccess: false,
            }))
          )
        );
    
        getBlogList(
          categoryID,
          Math.ceil(BlogStateBlogList.filter((blog) => (blog.category === categoryID)).size / DEFAULT_BLOG_LIST_SIZE)
        )
          .then((blogList) => {
            setTimeout(() => {
            // 以下使用BlogStateCategory等,最好加上 this.props.来使用store中的最新数据
              this.props.updateBlogStateCategory(
                this.props.BlogStateCategory.update(
                  this.props.BlogStateCategory.findIndex((categoryItem) => (categoryItem.get('id') === categoryID)),
                  (categoryItem) => (categoryItem.merge({
                    fetchPending: false,//数据读取结束后,将该状态更新为false
                    fetchFail: false,
                    fetchSuccess: true,
                  }))
                )
              );
    
              this.props.updateBlogStateBlogList(
                BlogStateBlogList.push(...List(blogList))
              );
            }, 500);
          })
          .catch(() => {
            this.props.updateBlogStateCategory(
              this.props.BlogStateCategory.update(
                this.props.BlogStateCategory.findIndex((categoryItem) => (categoryItem.id === categoryID)),
                (categoryItem) => (Object.assign(categoryItem, {
                  fetchPending: false,
                  fetchFail: true,
                  fetchSuccess: false,
                }))
              )
            );
          });
      }
    

    问题:
    第一次将count和fetch状态存入category成功,但获取List之后再更改category中的数据,会发现count不见了,只有fetch了。

    原因:原category被copy了两份,一份被用于步骤2,一份被用于步骤3。步骤2执行成功之后,count和fetch均被保存。但是后续的步骤3完成之后,步骤3中只更改了fetch,然后被存入category中,此时由于步骤3执行在后,在时间轴上,就将步骤2的跳过了,因此这个时候看数据,会发现是没有count的。

    解决办法:
    每次更改数据,都通过this.props.BlogStateCategory来获取最新的内容进行更改,而不是在一开始将它赋值于一个新变量,然后通过该变量来更新数据。因为它这个是内容的复制,然后再替换,而不是通过指针来修改的。
    换句话说,要改数据,可以,但请在最新的数据上进行更改,否则在这中间被更改过的数据将被最后一次更改的数据替换掉。

    2.导航切换时,状态更新有问题

    1.切换category,首先获取categoryID。
    2.然后根据categoryID判断当前是否有数据,有,就将内容筛选出来显示在页面上,如果没有,更改fetch状态为读取中并执行loading动画,然后获取List。
    3.List获取成功后,将列表存入store中,更改fetch状态为读取结束,页面上会自动根据fetch状态来判断是否显示Loading以及按钮文案。
    4.由于获取数据比较快,出现问题之后认为是两次更改太接近,导致没有看清,在获取成功后加了5s的延迟,结果是没有变化,store中的变化没有反映在页面上。
    5.或者在列表底部点击加载更多按钮,再内容显示出来之前,改变store中的pending状态,并更改按钮文案。

    出现的问题:
    切换不同的导航,可以看到fetch状态确实发生的更改,但是页面上的loading没有显示,按钮的文案也没有变化,一直是加载更多。

    原因:
    在一开始就已经通过fromJS将数据改变成不可变对象了,此时要更改数据内容,需要使用immutable的api来更改

    解决办法:
    更改用merge

    3.route设定indexRoute后,子页面跳转后,indexRoute会始终激活activeClassName。

    在“关于我们”这一模块中,嵌套了公共的menu,以及不同子页面的内容,导航上设置了activeClassName,但是页面跳转后,导航条上会有两个被激活的样式。

    解决办法:
    在route中不设置indexRoute,而是改为onEnter事件,对路由进行重定向。
    但此时又出现了一个新的问题,在子页,比如About/Career页面中时,切换到/about目录,此时不会进行重定向,原因是不会再一次进入onEnter事件。此时需要一个onChange事件,在路由更改后,根据判断来进行页面跳转。

    {
          path: '/about',
          getComponent(nextState, cb) {
            const importModules = Promise.all([
              System.import('AppContainers/About/reducer'),
              System.import('AppContainers/About'),
            ]);
            const renderRoute = loadModule(cb);
            importModules.then(([reducer, component]) => {
              injectReducer('about', reducer.default);
              renderRoute(component);
            });
            importModules.catch(errorLoading);
          },
          onEnter({ location }, replace) {
            if (location.pathname === '/about') {
              replace('/about/company');
            }
          },
          onChange(prevState, nextState, replace) {
            if (
              prevState.location.pathname !== nextState.location.pathname &&
              nextState.location.pathname === '/about'
            ) {
              replace('/about/company');
            }
          },
          childRoutes: [
            {
              path: 'company',
              getComponent(nextState, cb) {
                System.import('AppContainers/About/Company')
                  .then(loadModule(cb))
                  .catch(errorLoading);
              },
            }, {
              path: 'career',
              getComponent(nextState, cb) {
                System.import('AppContainers/About/Career')
                  .then(loadModule(cb))
                  .catch(errorLoading);
              },
            },
            {
              path: 'events',
              getComponent(nextState, cb) {
                System.import('AppContainers/About/Events')
                  .then(loadModule(cb))
                  .catch(errorLoading);
              },
            },
            {
              path: 'contact',
              getComponent(nextState, cb) {
                System.import('AppContainers/About/Contact')
                  .then(loadModule(cb))
                  .catch(errorLoading);
              },
            },
            {
              path: 'pr',
              getComponent(nextState, cb) {
                System.import('AppContainers/About/Pr')
                  .then(loadModule(cb))
                  .catch(errorLoading);
              },
            },
            {
              path: 'pr/:id',
              getComponent(nextState, cb) {
                System.import('AppContainers/About/PrDetail')
                  .then(loadModule(cb))
                  .catch(errorLoading);
              },
            },
            {
              path: 'faqs',
              getComponent(nextState, cb) {
                System.import('AppContainers/About/FAQs')
                  .then(loadModule(cb))
                  .catch(errorLoading);
              },
            },
            {
              path: 'privacy',
              getComponent(nextState, cb) {
                System.import('AppContainers/About/Privacy')
                  .then(loadModule(cb))
                  .catch(errorLoading);
              },
            },
            {
              path: 'terms',
              getComponent(nextState, cb) {
                System.import('AppContainers/About/Terms')
                  .then(loadModule(cb))
                  .catch(errorLoading);
              },
            },
            {
              path: 'feedback',
              getComponent(nextState, cb) {
                System.import('AppContainers/About/Feedback')
                  .then(loadModule(cb))
                  .catch(errorLoading);
              },
            },
          ],
        },
    

    4.react监听页面滚动事件

    首先是在页面中,当元素加载之前和加载之后,绑定滚动事件。

    constructor(props) {
        super(props);
        this.state = {
          sidebarFixed: false,
        };
      }
    componentWillMount() {
        window.addEventListener('scroll', this.handleScroll.bind(this));
      }
      componentDidMount() {
        window.addEventListener('scroll', this.handleScroll.bind(this));
      }
    handleScroll() {
        const scrollTop = document.body.scrollTop;
        const headerHeight = document.getElementById('header').offsetHeight;
        if (scrollTop >= headerHeight) {
          this.setState({ sidebarFixed: true });
        } else {
          this.setState({ sidebarFixed: false });
        }
      }
    

    这里会出现一个问题,就是当页面跳转时,该事件没有被解除,在其他页面进行页面滚动时,会报错。因为获取不到页面元素header的高度,所以当离开该页面的时候,需要解除绑定事件。

      componentWillUnmount() {
        window.removeEventListener('scroll', this.handleScroll.bind(this));
      }
    

    这时会发现,这个并没有其效果,原因在于我们是在事件中绑定的this,这里每次都是一个新的对象,因此没办法解除我们一开始绑定的事件对象。
    于是将代码更改为

     constructor(props) {
        super(props);
        this.state = {
          sidebarFixed: false,
        };
        this.handleScroll = this.handleScroll.bind(this);
      }
      componentWillMount() {
        window.addEventListener('scroll', this.handleScroll);
      }
      componentDidMount() {
        window.addEventListener('scroll', this.handleScroll);
      }
      componentWillUnmount() {
        window.removeEventListener('scroll', this.handleScroll);
      }
      handleScroll() {
        const scrollTop = document.body.scrollTop;
        const headerHeight = document.getElementById('header').offsetHeight;
        if (scrollTop >= headerHeight) {
          this.setState({ sidebarFixed: true });
        } else {
          this.setState({ sidebarFixed: false });
        }
      }
    

    好了,将事件在构造函数中绑定好,然后调用和解除的都是同一对象。

    相关文章

      网友评论

          本文标题:React + Redux 遇到的坑

          本文链接:https://www.haomeiwen.com/subject/uwqvzttx.html