Reactjs使用map循环遍历对象

时间:2017-02-05 23:21:10

标签: reactjs

我不确定这是什么类型的问题,但我有一个state.sports,其中包含一些有关体育的数据。我向此对象添加了新数据,然后我尝试使用此组件在DOM上呈现它。

class AddProject extends Component {
  constructor() {
    super();
    this.state = {
      newSport:{}
    }
    this.handleSubmit = this.handleSubmit.bind(this);
  }

  static defaultProps = {
      Types:['air','aquatic','land']
  }
  handleSubmit(e){
    if (!this.refs.sport.value) {
      alert("title required");
    } else {
      this.setState({
        newSport:{
          sport: this.refs.sport.value,
          type: this.refs.type.value
        }
      },function() {
        this.props.addSport(this.state.newSport);
      });
    }
    e.preventDefault();
  }
  render() {
    let typeOptions = this.props.Types.map(type => {
      return <option key={type} value={type}>{type}</option>
    });        
    return (
      <div className="addproject">
        <h3>Add project </h3>
        <form onSubmit={this.handleSubmit}>
          <div>
            <label>Sport </label><br/>
            <input type="text"
              key="sport"
              ref="sport"
            placeholder="Add project" />
          </div>
          <div>
            <label>Type</label><br/>
            <select ref='type'>
              {typeOptions}
            </select>
          </div>
          <input type='submit' value='Submit' />
        </form>
      </div>
    );
  }
}
export default AddProject;

然后我将此格式化数据添加到包含此组件的列表中:

class Project extends Component {

  render() {
    let Sports;
    //check if there is data in props.sports which is bind to state.sports
    if (this.props.sports) {
      Sports = this.props.sports.map(sport => {            
        return (
          //after some expirements i found that the key is the cause of the problem 
          <ProjectItems key={sport.name} sport={sport}  />
        );
      });
    }
    return (
      <div className="project">
        <h1>List </h1>
        <ul>
          {Sports}
        </ul>
      </div>
    );
  }
}

然后,ProjectItems将数据格式化为运动名称和运动类型。无论如何,当我输入一些数据时,它只会呈现运动类型,而运动的名称会返回undefined,例如here。你能告诉我什么是错的吗?

2 个答案:

答案 0 :(得分:0)

如果您提供ProjectItems类的代码会更清楚,但乍一看,在handleSubmit方法中,您应该改变这一点:

newSport:{
  sport: this.refs.sport.value,
  type: this.refs.type.value
}

到此:

newSport:{
  name: this.refs.sport.value,
  type: this.refs.type.value
}

答案 1 :(得分:0)

也许你想要实现的是在状态上设置嵌套对象属性。

使用这个:

 this.setState(
        {newSport: 
           update(this.state.newSport, 
            {type: {$set: this.refs.type.value}},
            {name: {$set: this.refs.sport.value}}
                )
         });

this.setState( {newSport: update(this.state.newSport, {type: {$set: this.refs.type.value}}, {name: {$set: this.refs.sport.value}} ) });

体育JSON结构将是:

 newSport: {type: "air", name: "land"}

的 然后你可以显示运动: newSport: {type: "air", name: "land"}