状态更改后,React不重新渲染

时间:2020-03-15 08:20:38

标签: reactjs django-rest-framework

import React, {Component, Fragment} from 'react'
import axios from 'axios'
import PropTypes from "prop-types";
import { connect } from 'react-redux'
import { postComment } from "../../../actions/comments"
import './styles.scss'

export class Comments extends Component {
    constructor(props) {
        super(props)

        this.state = {
            comment: "",
            author: null
        }
    }

    static propTypes = {
        postComment: PropTypes.func.isRequired
    };

    componentDidMount() {
        axios
        .get(`/api/auth/user`)
        .then(res => {
            const author = res.data.id
            this.setState({author});
        })
        .catch(err => console.log(err));
    }

    onSubmit(e) {
        e.preventDefault();
        const variables = {
            content: this.state.comment,
            post: this.props.post.id,
            author: this.state.author
        }
        this.props.postComment(variables)
        this.setState({content: ""});
    }

    onFieldChange(fieldName) {
        return function (event) {
            this.setState({[fieldName]: event.target.value});
        }
    }

    render() {
            return (
            <Fragment>
                   <div class="input">
                    <form style={{ display:'flex'}} onSubmit={e => this.onSubmit(e)}>
                         <div class="input-group">
                            <input 
                                class="form-control rounded-corner"
                                style={{width: '100%', borderRadius: '5px'}} 
                                onChange={this.onFieldChange('comment').bind(this)}
                                value = {this.state.comment}
                                placeholder="Leave a comments"
                            />
                            <span class="input-group-btn p-l-10">
                            <button class="btn btn-primary f-s-12 rounded-corner">Comment</button>
                            </span>
                         </div>
                      </form>
                </div>
                <div>

                    {/* Comment Lists */}...

                    ))}
                </div>
            </Fragment>
        );
    }
}

export default connect(
    null,
    { postComment }
)(Comments);

当我在帖子中添加评论时,这是一个页面,可以正常工作,但不会立即更新,因此我必须刷新。 componentDidMount方法使用axios获取当前用户,以为当前评论设置作者。提交表单后,我正在更改状态,我看不出问题所在。

0 个答案:

没有答案