【问题标题】:react call method within render渲染中的反应调用方法
【发布时间】:2018-06-20 15:36:54
【问题描述】:

如果 this.props.models 数组中只有一项,我会尝试自动调用我的方法 onModelSelect

{this.props.modelCheck && <div>{this.props.modelCheck.map(item => {()=>this.onModelSelect(item.id)} )}</div>}

如果我将该方法附加到 onClick 事件处理程序,它可以工作,但就其本身而言,我不确定要使用的语法,因为它在组件呈现时什么都不做

 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.modelCheck && <div>{this.props.modelCheck.map(item => {()=>this.onModelSelect(item.id)} )}</div>}
              {this.props.models.map(model =>
                <div onClick={()=> this.onModelSelect(model.id)}>Select Model</div>
              )}
            </div>
          )
        }
      }

      const mapStateToProps = (state) => {
        const modelCheck = getFilteredSelectableModels(state).length === 1 && getFilteredSelectableModels(state)

        return {
          modelCheck,
        };
      };

      const mapDispatchToProps = (dispatch) => {
        return bindActionCreators({
          ...settingDropActions,
        }, dispatch);
      };

      export default connect(mapStateToProps, mapDispatchToProps)(SettingDropModel);

【问题讨论】:

    标签: javascript reactjs


    【解决方案1】:

    为什么要将此行添加到渲染方法中:

    {this.props.models.length === 1 && this.props.models.map(model => ()=>this.onModelSelect(model.id))}
    

    首先,react JSX 中的.map 应该用于生成元素数组,这里不会发生这种情况。所以这个实现是不正确的。

    如果只有一个模型,要调用onModelSelect方法,你应该在componentDidMountreact生命周期方法中调用它。

    componentDidMount(){
        if(this.props.models.length === 1){
            this.onModelSelect(this.props.models[0].id);
        }
    }
    

    【讨论】:

    • 那行出错了,我会试着把它移到componentDidMount
    • 当你转到componentDidMount时它肯定会起作用。
    【解决方案2】:

    放入componentDidMount() 时不起作用,但放入componentWillReceiveProps() 时起作用

    componentWillReceiveProps(nextProps) {
        if(this.props.models.length === 1){
          this.onModelSelect(this.props.models[0].id);
        }
      }
    

    【讨论】:

    • 是的,这意味着组件this.props.models 的第一次渲染不可用。因此,您必须将其写入componentWillReceiveProps。但是有一个解决方法:您应该在componentWillReceiveProps 中使用nextProps 而不是this.props。理想情况下,您应该在两个函数中都编写它。
    猜你喜欢
    • 2018-11-29
    • 1970-01-01
    • 2020-12-02
    • 1970-01-01
    • 2018-06-23
    • 2016-10-30
    • 1970-01-01
    • 2015-07-03
    • 2020-05-19
    相关资源
    最近更新 更多