React JS - 如何在变量内设置变量的状态?

时间:2018-01-23 03:47:58

标签: reactjs state

我想设置此表单的状态:

this.state = {
  filter: {
    search: null,
    brands: null,
    price: null
  }
}

如何为搜索/品牌/价格设定价值?

8 个答案:

答案 0 :(得分:2)

关键是你不想改变状态中的值。因此,必须先复制过滤器对象,然后再将其传递给setState。例如:

this.state = {
   search: null,
   brands: null,
   price: null,
}

请注意,我将函数传递给setState。由于state的下一个值依赖于前一个值,因此您希望使用更新程序函数as the setState docs recommend

一般情况下,如果你能让你的州保持平稳,那就更好了。因此,不是将过滤器对象置于状态,您的形状可能只是

onSearchChange(value) {
  this.setState({search: value})
}

在这种情况下,上面的onSearchChange函数只是

sudo apt-get install imagick-php5

眼睛肯定容易多了。

答案 1 :(得分:1)

您应该使用setState函数,您可以使用更新的数据设置过滤器

const newFilter = {...};
this.setState({filter: newFilter});

答案 2 :(得分:1)

执行以下操作:

this.setState({
  filter: {
    search: 'value',
    brands: 'value',
    price: 'value'
  }
})

答案 3 :(得分:1)

你应该避免直接改变React状态,有些函数可以为你做不可变的工作(ex Object.assign):

const currentFilter = this.state.filter;
const newFilter = Object.assign({}, currentFilter, {search: "new search", brands: [], price: 100});
this.setState({filter: newFilter});

ES 6:

const currentFilter = this.state.filter;
this.setState({
   filter: {
      ...currentFilter,
      search: "new search",
      brands: []
   }
});

答案 4 :(得分:1)

this.setState({
filter: {
      ...this.state.filter,
      search: "new search", 
      brands: 'value',
      price: 'value'
   }
});

您可以尝试使用Spread运营商。 如果需要保留以前的过滤器值。 其他明智的你可以,

this.setState({
    filter: {
          search: "new search", 
          brands: 'value',
          price: 'value'
       }
    });

答案 5 :(得分:1)

我建议避免使用嵌套对象并保持状态平坦。 e.g。

this.state = {
  brandsFilter: null,
  priceFilter: null,
  searchFilter: null,
};

反应中的组件状态实际上只不过是简单的键值对;这是setState支持的内容。当然,如果你真的想要,你可以拥有嵌套对象。但正如其他答案所表明的那样,支持这种方法可能是不必要的复杂。

答案 6 :(得分:1)

let newfilter = Object.assign({}, this.state.filter)

newfilter.search ="value";
newfilter.brands ="value";
newfilter.price ="value";

this.setState({
    filter:newfilter
})

答案 7 :(得分:-4)

您可以使用以下方式访问搜索,品牌和价格:

this.setState({
    filter.search = true,
    filter.brands = 'stackoverflow',
    filter.price = 1400
})

并访问它,就像通常的状态访问一样(this.state.filter.search)。

相关问题