下面是我的组件类。该组件似乎永远不会执行 componentWillUpdate(),即使我可以通过在 mapStateToProps 中返回之前记录来查看状态更新。状态 100% 更改,但组件不会刷新。
import React, { Component } from 'react'
import { connect } from 'react-redux'
import { search } from './mapActions'
import L from 'leaflet'
class Map extends Component {
componentDidMount() {
L.Icon.Default.imagePath = './images'
this.map = new L.Map('map', {
center: new L.LatLng(this.props.lat, this.props.lng),
zoom: this.props.zoom,
layers: L.tileLayer('http://{s}.tile.osm.org/{z}/{x}/{y}.png', {
attribution: '<a href="http://osm.org/copyright">OpenStreetMap</a> contributors'
})
})
}
componentWillUpdate() {
console.log('UPDATE MAP')
L.geoJson(this.props.data).addTo(this.map)
}
render() {
return <div id="map"></div>
}
}
const mapStateToProps = (state) => {
return {
isFetching: state.isFetching,
data: state.data
}
}
const mapDispatchToProps = (dispatch) => {
return {
search: (name) => {
dispatch(search(name))
}
}
}
export default connect(
mapStateToProps,
mapDispatchToProps
)(Map)
这是地图减速器:
const initialState = {
isFetching: false,
data: {}
}
export const map = (state = initialState, action) => {
switch(action.type) {
case 'REQUEST_SEARCH_RESULTS':
return Object.assign({}, state, {
isFetching: true
})
case 'RECEIVE_SEARCH_RESULTS':
return Object.assign({}, state, {
isFetching: false,
data: action.data
})
default:
return state
}
}
经过一些更多的测试和记录后,似乎当它将状态映射到props时,它用来映射到props的状态对象包含正确的数据,所以 state.map.data 是正确的,我可以看到从 fetch 返回。但是,当我在 componentWillUpdate() 中记录 this.props 时,数据对象在那里但为空。