我使用的是react-hook-form (https://react-hook-form.com/)。我想从react-hook-form内部分派操作。
在下面的例子中,当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);发布于 2019-12-06 23:43:36
使用带redux的分派与react-hook-form库无关。
如果您使用的是redux-hooks,这就是an alternative for 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
}如果您使用connect
import { connect } from 'react-redux';
function App({ dispatch }) {
// use dispatch
}
export default connect()(App);发布于 2019-12-09 12:59:58
我想通了。我正在使用combineReducers。它分心了。我应该像下面这样写。
combineReducers({
sample01: sample01Reducer, sample02: sample02Reducer, //Reducersclass Sample extends Component {
constructor(props){
super(props);
this.state = {
mode: 'input'
}
}
render() {
switch (this.props.sample01.mode) {
case 'input':
return (<App />);
case 'confirm':
return (<App01 />);
default:
return (<App02 />);
}
}
}
export default connect((state)=>state)(Sample);https://stackoverflow.com/questions/59215958
复制相似问题