Reactjs 如果我们在React中有两个计数器组件,我们是否必须复制计数器代码?

Reactjs 如果我们在React中有两个计数器组件,我们是否必须复制计数器代码?,reactjs,redux,react-redux,Reactjs,Redux,React Redux,在React/Redux中,如果我们的计数器组件代码是30行,假设我们希望一个计数器作为Count面条连接到Redux store,另一个计数器作为countDrink连接到Redux store,那么我们必须复制这30行代码吗 我不认为我们需要CounterNoodle.js和CounterDrink.js并连接到Redux,每个文件可能有40行长,这是大量重复的代码 或者,如果计数器是类组件或函数组件,我们可以重用代码吗?当然不可以,您可以保持基本组件相同,只需使用两个不同的组件创建两个连接

在React/Redux中,如果我们的计数器组件代码是30行,假设我们希望一个计数器作为Count面条连接到Redux store,另一个计数器作为countDrink连接到Redux store,那么我们必须复制这30行代码吗

我不认为我们需要CounterNoodle.js和CounterDrink.js并连接到Redux,每个文件可能有40行长,这是大量重复的代码


或者,如果计数器是类组件或函数组件,我们可以重用代码吗?

当然不可以,您可以保持基本组件相同,只需使用两个不同的组件创建两个连接的组件

请注意,两个连接的组件选择状态的不同部分,如果您的计数器需要分派操作,您可以使用mapDispatchToProps作为第二个参数

您不能将计数值传递给组件,从而允许您将任何值传递给它,而不管它位于状态的何处

比如:


const countSelector = (state) => {
  return {
    drinkCount: state.drinks.total,
    noodleCount: state.noodles.total
  }
}

function App() {
  const { drinkCount, noodleCount } = useSelector(countSelector) 

return <div>
  Drink:
  <Counter count={drinkCount} />

  Noodle:
  <Counter count={noodleCount} />
</div>

}
如果需要将计数器组件订阅到状态,还可以执行以下操作:


const countSelector = (type) => (state) => {
  return type === 'drink' ? state.drinks.total : state.noodles.total
}

function Counter({ type }) {
  const count = useSelector(countSelector(type))

  return <div>{count}</div>
}

<Counter type="drink" />
它们是connectfnForState、fnForDispatchCounter,但只是不同的fnForState和fnForDispatch吗?似乎必须在连接线的末尾有计数器

const countSelector = (type) => (state) => {
  return type === 'drink' ? state.drinks.total : state.noodles.total
}

function Counter({ type }) {
  const count = useSelector(countSelector(type))

  return <div>{count}</div>
}

<Counter type="drink" />