a_z*_*ula 0 reactjs redux react-redux
我是 React/Redux 绑定的新手,我将实现 Redux 组件,该组件具有刷新笑话的形式,并可能改变获取的笑话数量(默认为 1 个笑话):
import fetchJokes from '../actions/jokes';
import { connect } from 'react-redux';
class FormToRefresh extends React.Component {
constructor(props) {
super(props);
this.state = {value: 1};
this.handleInput = this.handleInput.bind(this);
this.handleSubmit = this.handleSubmit.bind(this);
}
handleInput(e) {
let input = e.target.value;
if(isNaN(input)||input > 10||input< 1) {
alert("Wrong input");
this.setState({value: 1});
} else {
this.setState({value: input})
}
handleSubmit(e) {
// this should trigger dispatching fetchJokes action
// but how to integrate dispatch() function here...
dispatch(fetchJokes(this.state.value));
}
render() {
return (
<div>
<form onSubmit={this.handleSubmit>
<label>Enter amount of jokes (from 1 to 10):
<input type="text" value={this.state.value} onInput={this.handleInput} />
</label>
<button type="submit">Refresh</button>
</form>
</div>)
}
}
export default connect()(FormToRefresh);
Run Code Online (Sandbox Code Playgroud)
通常,我查看指南https://redux.js.org/basics/usage-with-react#implementing-other-components,我倾向于实现基于类的组件而不是基于函数的组件。我对如何将 dispatch()方法集成到指南的 AddTodo 函数以及我应该如何在我的 FormToRefresh 类中实现它有一些误解?如果您发现任何其他错误,请告诉我。
当您不通过时mapDispatchToProps,connect 函数将dispatch作为组件的道具可用,因此您可以利用它
// bind the below function
handleSubmit = (e) => {
const { dispatch } = this.props;
dispatch(fetchJokes(this.state.value));
}
Run Code Online (Sandbox Code Playgroud)
或者
传递动作来连接像
// bind the below function
handleSubmit = (e) => {
const { fetchJokes } = this.props;
fetchJokes(this.state.value);
}
export default connect(null, { fetchJokes })(FormToRefresh);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
8397 次 |
| 最近记录: |