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

标签 javascript reactjs redux react-hook-form

我正在使用 react-hook-form ( https://react-hook-form.com/ )。 我想从 react-hook-form 内部调度 Action 。

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

但是我不知道如何通过 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>
  )
}

有人给我建议吗?

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);

最佳答案

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

如果您使用 redux-hooks ,即 an alternative for connect和一个更好的方法,如果你无论如何都使用钩子(Hook) react-hook-form:

React's new "hooks" APIs give function components the ability to use local component state, execute side effects, and more.

React Redux now offers a set of hook APIs as an alternative to the existing connect() Higher Order Component. These APIs allow you to subscribe to the Redux store and dispatch actions, without having to wrap your components in connect().

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

如果您使用 connect :

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

export default connect()(App);

关于javascript - 如何从 react-hook-form + Redux 调度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59215958/

相关文章:

javascript - JavaScript 的 AWS api 网关?

node.js - Socket.emit 不发送或 socket.on 不接收?

reactjs - 如何正确更改 RTK 查询中的响应数据?

javascript - 打开自定义协议(protocol)后关闭浏览器窗口

javascript - 如何从javascript中的url中删除查询字符串数组

javascript - NextJs - next.config.js - CSS 加载器 + 自定义 Webpack 配置

javascript - 导入 CommonJS 在 ES6 中无法正确解构

javascript - 无法在 ReactJs 中设置 null、getUserMedia 的属性 'srcObject'

javascript - 如何在不取消 API 调用的情况下使用 axios 设置超时?

reactjs - 如何使这个 JSX 代码更加通用以避免 React 中的代码重用?