有人可以帮我理解为什么 this.props 在我过滤后没有更新吗?
这是我的代码的精简版本
export default class AutoList extends React.Component {
constructor(props) {
super(props);
this.state = {
filterValue: 'all',
isHidden: true,
autoOptValue: ''
}
}
handleOnChangeBrand(evt) {
let selectedValue = evt.target.value;
this.setState({optionValue: selectedValue});
let filtered = this.props.autos.filter((auto) => {
if(auto.brands){
return auto.brands[0] === selectedValue;
}
return false;
});
console.log(this.props.auto) // still same number
console.log(filtered) // less autos. Actual filtered array
}
render() {
let autoDetail = this.props.autos.map(auto => {
return (
<Auto
key={auto.id}
id={auto.id}
name={auto.name}
brands={auto.brands ? auto.brands : false}/>
);
});
return (
<div>
<section>
<select id='autoFilter' className={this.state.isHidden ? 'u-is-hidden' : ''} onChange={this.handleOnChangeBrand.bind(this)} value={this.state.autoOptValue}>
<option value='brand1'> brand1 </option>
<option value='brand2'> brand2 </option>
</select>
</section>
<ul>
{autoDetail}
</ul>
</div>
);
}
所以基本上我有 this.prop.auto 是一个包含 100 个汽车的数组,每个都是一个带有品牌的对象(这是另一个数组),每个都有 2,3 个品牌。
我能够进行过滤,因为filtered
给我返回了一个包含过滤后的自动的数组,即正确的数组。
但此后,this.props.auto 不会更新,UI 也不会更新。
我做了类似的事情,但是按品牌对汽车进行排序,并且运行顺利。 我不明白这里有什么区别
最佳答案
this.props
在组件内实际上是不可变的,因此您无法更新 this.props.autos
的值。 Array#filter
也是一个纯函数,因此被过滤的数组不会改变,但会返回一个新过滤后的数组。这就是为什么当您在函数中记录 filtered
时,您会看到过滤后的数组,但 this.props.autos
未更改。
对此问题的简单答案是在渲染方法中进行过滤 - 我已为 optionValue
添加了 false 的初始状态,并在过滤器方法中检查此状态,如果是,则不进行过滤仍然是假的。
export default class AutoList extends React.Component {
constructor(props) {
super(props);
this.state = {
filterValue: 'all',
isHidden: true,
autoOptValue: '',
optionValue: false
}
}
handleOnChangeBrand(evt) {
let selectedValue = evt.target.value;
this.setState({optionValue: selectedValue});
}
render() {
const { optionValue } = this.state;
const autoDetail = this.props.autos
.filter((auto) => {
if (!optionValue) return true;
if(auto.brands){
return auto.brands[0] === optionValue;
}
return false;
})
.map(auto => {
return (
<Auto
key={auto.id}
id={auto.id}
name={auto.name}
brands={auto.brands ? auto.brands : false}/>
);
});
return (
<div>
<section>
<select id='autoFilter' className={this.state.isHidden ? 'u-is-hidden' : ''} onChange={this.handleOnChangeBrand.bind(this)} value={this.state.autoOptValue}>
<option value='brand1'> brand1 </option>
<option value='brand2'> brand2 </option>
</select>
</section>
<ul>
{autoDetail}
</ul>
</div>
);
}
关于javascript - React this.props 不更新,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43058537/