redux 如今使用Hooks,以前和如今的對比

原文:Redux Now Has Hooks. A Before and After Comparison react

今天react-redux團隊發佈了7.1.0版本,react-redux新增了鉤子!這裏有一個快速的比較應該怎樣改寫你的組件。 首先,簡要概述的新函數redux

  • useSelector:經過一個函數讓state做爲一個入參而後返回一個value。用於從state中獲取一個值。它能夠做爲mapStateToProps的替代
  • useDispatch: 返回一個dispatch對象的引用,它能夠做爲mapDispatchToProps替代
  • useStore :返回store的實例。通常不推薦

舊的例子:一個搜索表單

一個示例組件包含stores查詢和提交查詢,我想使這個示例儘可能簡單,因此你能夠想象一下,它的結果。api

import React from 'react'
import { connect } from 'react-redux'
const defaultSearchBar = ({ query, updateQuery, handleSearch }) => {
  const handleSubmit = (e) => {
    e.preventDefault()
    handleSearch(query)
  }
  const handleChange = e => updateQuery(e.target.value)
  return (
    <form onSubmit={handleSubmit}>
      <input
        name="search"
        value={query}
        onChange={handleChange}
      />
    </form>
  )
}
const mapStateToProps = state => ({
  query: state.query,
})
const mapDispatchToProps = dispatch => ({
  updateQuery: newQuery => dispatch({ type: 'UPDATE_QUERY', payload: newQuery }),
  handleSearch: newSearch => dispatch({ type: 'NEW_SEARCH', payload: newSearch }),
})
const connectedSearchBar = connect(
  mapStateToProps,
  mapDispatchToProps,
)(defaultSearchBar)
複製代碼

新的組件

在咱們新的例子中,有一些不一樣之處:咱們徹底不使用了connect,mapStateToProps, mapDispatchToProps這三個函數,這意味着咱們的組件再也不直接接受props,如今,咱們的形式是這樣的:bash

import React from 'react'
import { useSelector, useDispatch } from 'react-redux'
const hookedSearchBar = () => {
  const dispatch = useDispatch()
  const query = useSelector(state => state.query)
  const handleSubmit = (e) => {
    e.preventDefault()
    dispatch({ type: 'NEW_SEARCH', payload: query })
  }
  const handleChange = e => dispatch({ type: 'UPDATE_QUERY', payload: e.target.value })
  return (
    <form onSubmit={handleSubmit}>
      <input
        name="search"
        value={query}
        onChange={handleChange}
      />
    </form>
  )
}
複製代碼

建立本身的hooks

若是你的代碼組件之間頻繁使用(我理解是頻繁調用),您能夠建立一個hooks,將全部的功能結合在一塊兒. 這裏有個例子,咱們單獨把redux 特殊的部分造成本身的hooks函數

你應該使用開關嗎?

可以建立上面的鉤子是很是有趣的,可是我也擔憂,它可能會使代碼難以測試。爲測試這些組件已經危險。我不是推銷的形式,但我但願這對你比較更容易對代碼庫作出明智的決定測試

相關文章
相關標籤/搜索