1

我需要将道具传递给我的初始状态以进行编辑表单(因为我希望表单的值等于状态)但我似乎无法让它工作。该组件没有将道具提供给initialState,因为它首先加载一个空道具,我认为是由于createContainer。我尝试了很多东西(componentDidMount、WillMount、WillReceiveProps...),但没有成功。代码如下,有什么帮助吗?

import React from 'react';
import PropTypes from 'prop-types';
import { Meteor } from 'meteor/meteor';
import moment from 'moment';
import { createContainer } from 'meteor/react-meteor-data';

import { Blogposts } from './../api/blogposts';

export class BlogpostEditItem extends React.Component {

constructor(props){
    super(props);
    this.state = {
        title: this.props.blogpost.title,
        body: this.props.blogpost.body
    }
}

handleBodyChange(e) {
    const body = e.target.value;
    this.setState({ body });
}

handleTitleChange(e) {
    const title = e.target.value;
    this.setState({ title   });
}

onSubmit(e) {
    e.preventDefault();
    this.props.call('blogposts.update', this.props.blogpost._id, this.state.title, this.state.body,);
}

renderEditForm() {
    return(
        <div>
            <input onChange={this.handleTitleChange.bind(this)} value={this.state.title} placeholder="Title" type="text"/>
            <textarea onChange={this.handleBodyChange.bind(this)} value={this.state.body} placeholder="Body"></textarea>
            <button onClick={this.onSubmit.bind(this)}>Submit Blogpost</button>
        </div>
    )
}

render() {
    return (
        <div>
            { this.props.blogpost ? this.renderEditForm() : 'Pas de post' }
        </div>
    );
}
}

export default createContainer(({params}) => {
    Meteor.subscribe('blogposts');

    return {
        blogpost: Blogposts.findOne(params.id),
        call: Meteor.call
    }   
}, BlogpostEditItem)

我还尝试将道具作为 defaultValue 传递并将状态保持为值,但它不允许在表单上同时具有这两者。知道如何解决我的问题吗?提前致谢。

4

1 回答 1

2

构造函数内部你得到的props不是this.props 在构造函数之外,你应该继续this.props

constructor(props){
    super(props);
    this.state = {
        title: props.blogpost.title,
        body: props.blogpost.body
    }
}

于 2017-08-16T10:28:01.227 回答