【问题标题】:React/Meteor - this.state from props gets undefinedReact/Meteor - 来自 props 的 this.state 未定义
【发布时间】:2018-01-24 10:40:11
【问题描述】:

我需要将道具传递给我的初始状态以进行编辑表单(因为我希望表单的值等于状态)但我似乎无法让它工作。该组件没有将道具提供给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 传递并将状态保持为值,但它不允许在表单上同时具有这两者。知道如何解决我的问题吗? 提前致谢。

【问题讨论】:

    标签: reactjs meteor state react-props react-state


    【解决方案1】:

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

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

    【讨论】:

    • 我现在感到非常惭愧 :D 非常感谢队友!
    • @Ivo:如果你能把它标记为答案就好了:)
    • 你拯救了我的一天
    猜你喜欢
    • 2020-10-16
    • 2017-03-30
    • 1970-01-01
    • 2017-12-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-08-06
    相关资源
    最近更新 更多