我只是尝试做类似的事情(当用户选择时,继续使用其他组件):
render() {
return(
<select onChange={(e)=> <CountrySelected countrySelected=
{e.target.value}/> }>
{this.state.countryArray.map( (e) => <option> {e.name} </option>) }
</select>
);
}
即使我做不到,所以请继续阅读下一个代码,告诉我如何解决以下问题: 以下代码对我来说很有效:
class App extends Component {
state = {
countryArray: [],
selectedCountry: undefined
};
constructor(p) {
super(p);
// here i'm Initializing the this.state.countryArray
}
countrySelectionHandler=(countryName)=> {
this.setState({ selectedCountry:
this.state.countryArray.find(e=>e.name===countryName) });
}
render() {
return (
<div>
<CountryDropDown
countryArray={this.state.countryArray}
countrySelectionHandler={this.countrySelectionHandler} />
{
this.state.selectedCountry ?
// this component just display on the screen the selectedCountry name
<CountryName countryName={this.state.selectedCountry.name} />
:
<div> no country selected</div>
}
</div>
);
}
}
“ CountryDropDown”组件:
const countryDropDown = (p)=>(
<select onChange={(e)=> p.countrySelectionHandler(e.target.value)}>
{p.countryArray.map( (e) => <option> {e.name}
</option>) }
</select>
)
但是现在当用户选择时,它将无缘无故地重新渲染“ CountryDropDown”组件。 所以我该如何打电话以仅重新渲染此部分:
{
this.state.selectedCountry ?
// this component just display the selectedCountry name
<CountryName countryName={this.state.selectedCountry.name} />
:
<div> no country selected</div>
}
所以我尝试解决它的方式: 当用户选择时,继续使用其他组件(CountrySelected),仅显示“ CountryName”组件
答案 0 :(得分:0)
如果不使用PureComponent或自定义的shouldComponentUpdate生命周期函数。 当父组件重新渲染时,子组件将被重新渲染。
class CountryDropDown extends Component {
shouldComponentUpdate(nextProps) {
return (this.props.countryArray !== nextProps.countryArray)
}
render() {
const { countrySelectionHandler, countryArray } = this.props
return (
<select onChange={countrySelectionHandler}>
{countryArray.map((e) => <option> {e.name}
</option>)}
</select>
)
}
}
PureComponent
class CountryDropDown extends PureComponent {
render() {
const { countrySelectionHandler, countryArray } = this.props
return (
<select onChange={countrySelectionHandler}>
{countryArray.map((e) => <option> {e.name}
</option>)}
</select>
)
}
}
默认情况下,PureComponent具有浅表比较shouldComponentUpdate函数。