反应在渲染中调用绑定方法

时间:2018-06-20 09:50:04

标签: javascript reactjs

我试图在render()中调用方法onModelSelect

如果我将其命名为this.onModelSelect(model.id)),则会收到错误Warning: setState(...): Cannot update during an existing state transition (such as within渲染). Render methods should be a pure function of props and state.,但是它确实输出到console.log

因此,我试图像使用事件处理程序()=>this.onModelSelect(model.id))一样调用它,但这不会向console.log输出任何内容

用来调用我的方法的正确语法是什么?

export default class App extends Component {
          render() {
            onModelSelect = (modelId) => {
              this.props.selectModel(modelId);
              this.props.setModelSelected(true);
              console.log('test')
              console.log('modelId',modelId)
            }
              return(
                <div>
                  {this.props.models.length === 1 && this.props.models.map(model => ()=>this.onModelSelect(model.id))}
                </div>
              )
          }
      }

3 个答案:

答案 0 :(得分:0)

您不应从渲染方法中调用包含this.setState的任何内容。

实际上,您的this.onModelSelect(model.id)将返回Undefined function error,因为必须在组件中而不是在onModalSelect函数中定义render()函数

export default class App extends Component {
        onModelSelect = (modelId) => {
          this.props.selectModel(modelId);
          this.props.setModelSelected(true);
          console.log('test')
          console.log('modelId',modelId)
        }

      render() {
          return(
            <div>
              {this.props.models.length === 1 && this.props.models.map(model => ()=>this.onModelSelect(model.id))}
            </div>
          )
      }
  }

答案 1 :(得分:0)

尝试将onModelSelect方法放在render方法之外

答案 2 :(得分:0)

这样写时会出现问题:

.map(model => ()=>this.onModelSelect(model.id))

这表示.map回调返回函数,而该函数又需要调用才能执行您的函数。相反,它应该是:

.map(model => this.onModelSelect(model.id))

另外.map回调函数应返回一些值,这些值将附加到数组并呈现在元素内部。

您应在渲染函数外部创建onModelSelect方法:

export default class App extends Component {
          onModelSelect = (modelId) => {
              this.props.selectModel(modelId);
              this.props.setModelSelected(true);
              console.log('test')
              console.log('modelId',modelId)
            }

          render() {
              return(
                <div>
                  {this.props.models.length === 1 && this.props.models.map(model => this.onModelSelect(model.id))}
                </div>
              )
          }
      }

或者,如果有合法的用例,并且您想将其放入render函数中,则直接调用它,而不用此方法。考虑下面的代码:

export default class App extends Component {
      render() {
        let onModelSelect = (modelId) => {
          this.props.selectModel(modelId);
          this.props.setModelSelected(true);
          console.log('test')
          console.log('modelId',modelId)
        };
          return(
            <div>
              {this.props.models.length === 1 && this.props.models.map(model => onModelSelect(model.id))}
            </div>
          )
      }
  }