我正在使用 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/