如何从 react-hook-form + Redux 调度

taj*_*iro 3 javascript reactjs redux react-hook-form

我正在使用 react-hook-form ( https://react-hook-form.com/ )。我想从 react-hook-form 内部发送动作。

在以下情况下,props.dispatch当 onSubmit 被触发时,我应该使用,进行调度。

但是我不知道如何通过 setState 调度和更新状态。

import React from 'react'
import useForm from 'react-hook-form'

export default function App(props) {
  const { register, handleSubmit, watch, errors } = useForm()
  const onSubmit = data => { 
           console.log(data);
           props.dispatch({type: 'CONFIRM'}); //--> Worked!!  
        }

  console.log(watch('example')) // watch input value by passing the name of it

  return (
    <form onSubmit={handleSubmit(onSubmit)}>
      <input name="example" defaultValue="test" ref={register} />
      <input name="exampleRequired" ref={register({ required: true })} />      
      <input type="submit" />
    </form>
  )
}
Run Code Online (Sandbox Code Playgroud)

有人给我建议吗?

class Sample extends Component {
    constructor(props){
        super(props);
        this.state = {
            mode: 'input'
        }
    }

    render() {
        switch (this.state.mode) {
            case 'input':
                return (<App />);
            case 'confirm':
                return (<App01 />);
            default:
                return (<App02 />);
        }
    }
}

export default connect((state)=>state)(Sample);
Run Code Online (Sandbox Code Playgroud)

Den*_*ash 5

在 redux 中使用 dispatch 与react-hook-form库无关。

如果您使用redux-hooks,如果您无论如何都使用钩子,这是一种替代方法connect和更好的方法react-hook-form

React 的新“钩子”API 使函数组件能够使用本地组件状态、执行副作用等。

React Redux 现在提供了一组钩子 API 作为现有 connect() 高阶组件的替代方案。这些 API 允许您订阅 Redux 存储和分派操作,而无需将组件包装在 connect() 中。

import { useDispatch } from 'react-redux';
function App() {
  const dispatch = useDispatch();
  // use distpach
}
Run Code Online (Sandbox Code Playgroud)

如果您使用connect

import { connect } from 'react-redux';
function App({ dispatch }) {
  // use dispatch
}

export default connect()(App);
Run Code Online (Sandbox Code Playgroud)