重构 - mapProps和withProps不更新道具

时间:2017-08-27 20:03:48

标签: javascript reactjs recompose

我有一个容器,我想管理名册排序顺序,方向和性别过滤器。我在下面的当前withProps代码中尝试了mapPropswithProps,名单在withProps内得到正确更新,但它没有覆盖现有的名单摔跤手组件

import { compose, withState, withProps, withHandlers } from "recompose"
import { connect } from "react-redux"
import sortBy from "lodash/sortBy"


// container
export default compose(
  withState("male", "toggleGender", true),
  withState("sortByName", "toggleSortByName", true),
  withState("order", "toggleOrder", true),
  withHandlers({
    toggleGender: ({ toggleGender, male, }) => () => toggleGender(!male),
    toggleSortByName: ({ toggleSortByName, sortByName, }) => () =>
      toggleSortByName(!sortByName),
    toggleOrder: ({ toggleOrder, order, }) => () => toggleOrder(!order),
  }),
  connect(state => ({
    roster: state.roster,
  })),
  withProps(props => {
    const { roster, toggleOrder, male, sortByName, } = props

    let newRoster = Object.assign([], roster)

    newRoster = newRoster.filter(wrestler => wrestler.male === male)

    if (toggleOrder) {
      newRoster = newRoster.reverse()
    }

    newRoster = sortBy(newRoster, sortByName ? "name" : "points")

    return {
      roster: newRoster,
      ...props,
    }
  })
)(Wrestlers)

1 个答案:

答案 0 :(得分:3)

那太傻了,我需要改变回归的顺序,我还修了一些其他的未成年人

import { compose, withState, withProps, withHandlers } from "recompose"
import { connect } from "react-redux"
import sortBy from "lodash/sortBy"

import Wrestlers from "./wrestlers"

export default compose(
  withState("male", "toggleGender", true),
  withState("sortByName", "toggleSortByName", true),
  withState("order", "toggleOrder", true),
  withHandlers({
    toggleGender: ({ toggleGender, male, }) => () => toggleGender(!male),
    toggleSortByName: ({ toggleSortByName, sortByName, }) => () =>
      toggleSortByName(!sortByName),
    toggleOrder: ({ toggleOrder, order, }) => () => toggleOrder(!order),
  }),
  connect(state => ({
    roster: state.roster,
  })),
  withProps(props => {
    const { roster, order, male, sortByName, } = props

    let newRoster = Object.assign([], roster)

    newRoster = newRoster.filter(wrestler => wrestler.male === male)

    newRoster = sortBy(newRoster, sortByName ? "name" : "points")

    if (order) {
      newRoster = newRoster.reverse()
    }

    return {
      ...props,
      roster: newRoster,
    }
  })
)(Wrestlers)