我有一个带有prop的组件,它是一个对象数组。
问题是它在constructor()
中是空的,即使其他具有原始值的道具也填充在render()
中,它也被填充。
为什么会这样,我如何在构造函数中传递数组?
组件:
import React, { Component } from "react";
import { Dropdown } from "semantic-ui-react"
class SearchableDropdown extends Component {
defaultOptions = []
allOptions = []
constructor(props) {
super(props)
console.log(props.options) //empty here
}
search = (event, { searchQuery }) => {
console.log(searchQuery)
}
render () {
console.log(this.props.options) //but filled here
return (
<Dropdown selection search onSearchChange={this.search} {...this.props}/>
)
}
}
export { SearchableDropdown }
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
组件渲染:
<SearchableDropdown name='city' value={city} onChange={this.handleChange} placeholder='City' options={this.props.cities}/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
答案 0 :(得分:1)
由于options
道具需要一段时间才能到达SearchableDropdown
组件。
您需要使用componentWillReceiveProps()
constructor(props) {
super(props)
console.log(props.options) //empty here
this.state = {
options: null, // options should be here
}
}
componentWillReceiveProps(nextProps){
if(nextProps.options !== this.props.options){
this.setState({ options: nextProps.options })
}
}
search = (event, { searchQuery }) => {
console.log(searchQuery)
}
render () {
console.log(this.props.options) //but filled here
return (
<Dropdown selection search onSearchChange={this.search} {...this.props}/>
)
}
}
答案 1 :(得分:0)
尝试使用componentDidMount()
代替constructor()
。也许问题是因为当调用constructor()
时,父组件甚至没有安装,所以道具还没有通过。
试一试:
class SearchableDropdown extends Component {
constructor(props){
super(props)
}
componentDidMount(){
console.log(this.props.options)
}
// ... rest of the code
}