React:如何将绑定方法绑定到状态中的数组中的元素[重复]

问题描述 投票:0回答:1

这个问题在这里已有答案:

我花了大约20个小时试图弄清楚如何做到这一点,所以任何建议都会非常感激。

我想要做的是在我的表示组件中,调用从更高阶组件传递下来的方法,然后该方法将改变在更高容器中处理的状态。

我的高阶容器看起来像这样:

export default class TodayContainer extends Component {
  constructor(props) {
    super(props);

    this.state = {goalItems: [{id: 1, goal: "Pet the dog"}, {id: 2, 
    goal: "feed the cat"}, {id: 3, goal: "other good stuff"}]};

    this.goalSave = this.goalSave.bind(this);

  }

  goalSave(goal) {
    let stateCopy = Object.assign({}, this.state);
    stateCopy.goalItems[key].goal = goal;
    this.setState(stateCopy); }

render() {
    return (
      <Today goalItems={this.state.goalItems}
             goalSave={this.goalSave}/>
    )}}

使用[key]在goalSave方法中存在一个问题,我还没有想出如何映射正确的数组值,(也很高兴在那里提供建议),但我还没有调试那个,因为我可以'正确传递任何方法。

我的道具通过几个表达容器传递下来。这是我第一次与他们合作的地方。

  CreateGoalItems() {
    const goalObjects = this.props.goalItems;
    if( goalObjects === undefined ) {
      return <div>Loading...</div>
    }

    let test = [];
     Object.keys(goalObjects).forEach(function(key) {

     test.push(<GoalItem key={goalObjects[key].id}
       goal={goalObjects[key].goal}
       goalSave={this.props.goalSave} />)   //**Doesn't Work ***
    });
    return test;
  }

在上面,我能够正确传递目标,但我无法弄清楚如何传递该方法。当我在状态中只有一个对象而不是数组时,我没有遇到任何麻烦,但是对于数组我不知道如何将该方法绑定到我的GoalItem组件的特定实例。我得到“this.props.goalSave不是函数”错误。

注意:如果传递类似的函数,我会得到相同的错误

doNothing() {
  console.log("This did nothing");
}

我很丢失。预先感谢您的任何帮助。

javascript reactjs
1个回答
0
投票

您是否尝试在从goalSave传入之前保存props函数的引用?

CreateGoalItems() {
    const goalObjects = this.props.goalItems;
    const goalSave = this.props.goalSave;     
    if( goalObjects === undefined ) {
        return <div>Loading...</div>
    }

    let test = [];
    Object.keys(goalObjects).forEach(function(key) {
        test.push(<GoalItem key={goalObjects[key].id}
        goal={goalObjects[key].goal}
        goalSave={goalSave} />) 
    });
    return test;
}
© www.soinside.com 2019 - 2024. All rights reserved.