【发布时间】:2016-06-25 08:09:39
【问题描述】:
下面是我的组件类。该组件似乎永远不会执行 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
}
}
经过更多的测试和记录后,似乎当它去映射状态到道具时,它用来映射到道具的状态对象包含正确的数据,所以 state.map.data 是正确的,我可以看到从拿来。但是,当我在 componentWillUpdate() 中记录 this.props 时,数据对象在那里但为空。
【问题讨论】:
-
你能展示你的减速器吗?可能是你改变了状态而不是发送新对象,所以 redux 认为没有理由更新。
-
render中没有任何内容:<div id="map"></div> -
@DavinTryon 我正在使用 Leaflet 来处理它自己的渲染,但它仍然应该像在更新组件一样。
-
@Mijamo 我已经添加了,谢谢。
标签: javascript reactjs state redux