class States extends Component {
componentDidMount() {
this.props.getForSaleStates()
}
render() {
return (
<div>
{this.props.post.states.map((eachState, index) => (
<State key={index} eachState={eachState} />
))}
</div>
)
}
}
const mapStateToProps = state => ({
post: state.post,
auth: state.form
})
export default connect(mapStateToProps, {
getForSaleStates
})(States)
class State extends Component {
state = {
isOpen: false,
cities: []
}
componentDidUpdate(prevProps) {
if (this.props.post.cities !== prevProps.post.cities) {
this.setState({
cities: this.props.post.cities
})
}
}
handleClick = (e) => {
if (!this.state.isOpen) {
this.props.getForSaleTowns(this.props.eachState)
}
this.setState({
isOpen: !this.state.isOpen
})
}
render() {
console.log(this.state)
return (
<div>
<ListGroupItem
style={{ fontSize: '12px' }} className='p-0 border-0'
tag="a" href="#"
onClick={this.handleClick}>
{!this.state.isOpen ? (
<i className="far fa-plus-square mr-1" style={{ fontSize: '1em' }}>
</i>
) : (
<i className="far fa-minus-square mr-1" style={{ fontSize: '1em' }}>
</i>
)}
{this.props.eachState}
</ListGroupItem>
<Collapse isOpen={this.state.isOpen}>
<Cities cities={this.state.cities} />
</Collapse>
</div>
)
}
}
const mapStateToProps = state => ({
post: state.post,
auth: state.form
})
export default connect(mapStateToProps, { getForSaleTowns })(State)
class Cities extends Component {
render() {
// console.log(this.props)
return (
<div>
<ListGroup >
{this.props.cities.map((city, index) => (
<ListGroupItem key={index} style={{ fontSize: '11px' }} className='border-0' tag="a" href="#">
{city}
</ListGroupItem>
))}
</ListGroup>
</div>
)
}
}
const mapStateToProps = state => ({
post: state.post,
auth: state.form
})
export default connect(mapStateToProps)(Cities)
说明:州=>省=>城市
从数据库中获取所有州,将它们映射到彼此具有各自的州,然后通过向redux发送另一个操作并在该州中获取镇来调用该州中的镇。
上面的代码工作正常,唯一的事情是当我单击一个州时,崩溃会打开并显示该州的城镇。但是,如果我单击另一个州,则来自redux的城镇会发生变化,因此上面的列表也会发生变化。
这是一张解释我的意思的照片:
我如何做到这一点,以便每个州都列出自己的城市,而不是全部都变得相同
答案 0 :(得分:0)
componentDidUpdate(prevProps) {
if (this.props.post[state_id].cities !== prevProps.post[state_id].cities) {
this.setState({
cities: this.props.post.cities
})
}
}
post Reducer
export const postReducer = (state, action) => {
[...Old code]
case [TOWN_FETCH_SUCCESS]:
return {
...state,
// your unique identifier for each state
[state_id]: action.payload
}
}
在保存时,您可以在该州的ID中保存城镇