javascript - 如何从 Textarea 分派一个值来存储 React Redux
问题描述
我对如何通过调度传递 textarea 值并保存到存储有疑问。
我的减速机是这样的:
var defaultCommentState = {
login_status: false,
author_name: '',
author_email: '',
author_url: 'https://google.com',
content: '',
post:null,
parent:0
}
const addComment = (state = defaultCommentState, action) => {
switch(action.type) {
case 'ADD_COMMENT_CONTENT':
return {
...state,
content: action.content
}
default:
return state;
}
}
export default addComment;
我的表格是这样的:
<form name="post_comment" className="post-a--comment" onSubmit={this.handleSubmit}>
<div className="thecmstatus" />
<label>Message (You signed in as <span>{author_name}</span>)</label>
<textarea id="content"
onChange={this.handlecontent}
value={this.state.content}
required="required" /> <br/>
<button type="submit"
id="blog_post_submit"
className="btn-default btn">
Submit
</button>
</form>
我的动作是这样的:
const addcommentcontent = (content) => {
return {
type: 'ADD_COMMENT_CONTENT',
content
}
}
我可以通过函数调度状态变化,onChange
但这是个好方法。
handleSubmit = (e) => {
e.preventDefault();
this.setState({
...this.props.addComment,
content:this.props.content
})
this.props.onSubmit(this.props.addComment);
}
handlecontent = (e) => {
this.setState({
content: e.target.value
})
//I dispatch on state change but I think it is not good
const {commentcontentadded} = this.props;
commentcontentadded(this.state.content);
}
你能告诉我如何通过调度将 textarea 值传递给存储,因为我需要从存储提交有效负载而不是像这样的状态。
this.props.onSubmit(this.props.addComment)
解决方案
导入 Action creator (addcommentcontent),并在 handleSubmit 方法中调度他。
handleSubmit = (e) => {
e.preventDefault();
this.setState({
...this.props.addComment,
content:this.props.content
})
dispatch(addcommentcontent(this.state.content));
}
推荐阅读
- java - 在 Hibernate 上连接任何类型映射的查询
- c - C中的大小写可变宏
- python - 如何将自定义训练的 PyTorch 模型集成到 OpenCV 的 dnn 模块中?
- javascript - javascript 和 jquery 无法正常工作我的 php 页面?
- python - 使用openpyxl将二维列表的元素插入到excel中
- elasticsearch - Elasticsearch:找出主分片的运行节点名称?
- python - 有没有办法在 MongoDB 中从 INT 创建 ObjectID?
- mongodb - 如何保存多个for循环数据?
- c# - 单击按钮时显示 Groupbox 或将 GroupBox 置于前面?
- rust - 如何通过适配器在一行中重复或连接两个切片 n 次?