从Meteor数据

时间:2017-06-28 18:51:49

标签: reactjs meteor state

开发!有谁可以帮助我吗? 我正在尝试从Meteor中的React设置state并从输入中编辑此state数据,它看起来像

class Profile extends Component{
  constructor(props){
    super(props);
    this.editProfileBind = this.editProfile.bind(this);
    this.testEmailBind = this.testEmail.bind(this); }

  testEmail(e){
    const input = e.target;
    this.setState({
      email: input.value
    });
    input.value = this.state.email;
  }

  editProfile(e){
      e.preventDefault();
  }

  render(){
    return(
         <form className="col-md-4 col-xs-6" 
             onSubmit={this.editProfileBind}>
             <input type="email"
                  onChange={this.testEmailBind}
                  value={this.props.email || ''}
                />
           <button type="submit">Submit</button>
        </form>
   )
 }
}  // end component

export default createContainer(() => {
    const user = Meteor.user();
    const email = user.emails && user.emails[0].address;

    return { email };
}, Profile);

您能否建议我如何设置this.state.email来代替this.props.email?谢谢!

1 个答案:

答案 0 :(得分:4)

对代码产生问题:

<强> 1。使用道具初始化州

在构造函数中,您需要将初始状态设置为传入的email道具。

<强> 2。输入value应该等于this.state.email

该值未更新,因为您要将值设置为传入的prop(不会更改),而不是email函数正在更新的testEmail状态。

第3。使用新道具更新州

您需要添加componentWillReceiveProps函数,以便在将新数据传递到email组件时更新Profile状态。

Profile组件应如下所示:

class Profile extends Component{
  constructor(props){
    super(props);
    this.editProfileBind = this.editProfile.bind(this);
    this.testEmailBind = this.testEmail.bind(this); 
    this.state = {
        email: props.email
    }
  }

  testEmail(e){
    const input = e.target;
    this.setState({
      email: input.value
    });
  }

  editProfile(e){
      e.preventDefault();
  }

  componentWillReceiveProps(nextProps){
    this.setState({
        email: nextProps.email
    });
  }

  render(){
    return(
         <form className="col-md-4 col-xs-6" 
             onSubmit={this.editProfileBind}>
             <input type="email"
                  onChange={this.testEmailBind}
                  value={this.state.email}
                />
           <button type="submit">Submit</button>
        </form>
   )
 }
}  // end component

export default createContainer(() => {
    const user = Meteor.user();
    const email = user.emails && user.emails[0].address;

    return { email };
}, Profile);