首页 > 解决方案 > 如何从 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)

标签: javascriptreactjsreact-redux

解决方案


导入 Action creator (addcommentcontent),并在 handleSubmit 方法中调度他。

handleSubmit = (e) => {
    e.preventDefault(); 
    this.setState({
        ...this.props.addComment,
        content:this.props.content
    })
    
    dispatch(addcommentcontent(this.state.content));
}


推荐阅读