Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/444.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 只有当事物存在时,才对状态作出反应?_Javascript_Jquery_Reactjs - Fatal编程技术网

Javascript 只有当事物存在时,才对状态作出反应?

Javascript 只有当事物存在时,才对状态作出反应?,javascript,jquery,reactjs,Javascript,Jquery,Reactjs,因此,我正在设置一个具有多个状态属性的父对象,以传递给子对象。这是通过AJAX实现的。问题在于,对于其中一些变量,响应可能返回null或undefined $.post(this.props.source, function(data) { // Parse the response var response = JSON.parse(data); if (this.isMounted()) { this.setState({ // Set initial

因此,我正在设置一个具有多个状态属性的父对象,以传递给子对象。这是通过AJAX实现的。问题在于,对于其中一些变量,响应可能返回
null
undefined

$.post(this.props.source, function(data) {

  // Parse the response
  var response = JSON.parse(data);

  if (this.isMounted()) {
    this.setState({

      // Set initial state vars
      minPrice:         response.resultDetails.minPrice,
      maxPrice:         response.resultDetails.maxPrice,
      language:         response.params.language,
      filters:          response.params.filters

    });
  }
}.bind(this));

如果response.params.language和set language都是
,我怎么说呢?我搞不懂做这种事的反应语法

  • 您应该在
    componentDidMount
    中执行此操作,因此无需检查
    isMounted
  • 如果指定
    数据类型
    ,那么jQuery将为您执行json解析,并且数据已经是一个对象
  • 如果
    response.params.language
    是falsy(未定义),那么设置它又有什么关系呢?因为您正在重写一个非falsy值
  • 你可以用很多方法来做到这一点。。这与反应无关。e、 g:

    var newState = {
      minPrice: response.resultDetails.minPrice,
      maxPrice: response.resultDetails.maxPrice,
    };
    
    if (response.params.language) {
      newState.language = response.params.language;
    }
    
    if (response.params.filters) {
      newState.filters = response.params.language;
    }
    
    this.setState(newState);
    
    或:


    if(response.params.language)this.setState({language:response.params.language})等等?根据React文档,我在
    组件中安装了
    ismount
    。不过,干杯,最后用Trimal.Np解决了这个问题,我想如果您的组件未安装,可能会有风险-可能值得一看,因为iMounted已被弃用,啊,我不知道。奇怪的是,它仍然存在于官方文件中。所以您建议只在
    componentDidMount
    内部执行此操作?是的,如果您担心组件可能会在请求完成之前卸载,那么您可以在
    componentDidMount
    this中设置var
    this.\u isMounted=true
    ,并在
    componentWillUnmount
    中使用该变量进行检查
    this.setState({
          minPrice: response.resultDetails.minPrice,
          maxPrice: response.resultDetails.maxPrice,
          language: response.params.language || this.state.language,
          filters: response.params.filters  || this.state.filters
    });