在分派(dispatch)操作之前,我需要访问存储中的属性,在容器中(代码如下所示),我使用 store.getState()
来访问它。
我想知道它是否正确或者是否存在更合适的方法。
import { connect } from 'react-redux'
import LocationFinderSearch from './locationFinderSearch'
import { getLocations, setSearchValue } from './locationFinderSearchActions'
import store from '../app/store'
const mapStateToProps = (state, ownProps) => {
return {
}
}
const mapDispatchToProps = (dispatch, ownProps) => {
return {
onLocationSearchClick: (e) => {
e.preventDefault()
let value = store.getState().locationFinderReducer.locationFinder.ui.inputValue
dispatch(getLocations(value))
},
onLocationInputChange: (e) => {
e.preventDefault()
let value = e.target.value
dispatch(setSearchValue(value))
}
}
}
const LocationFinderSearchContainer = connect(
mapStateToProps,
mapDispatchToProps
)(LocationFinderSearch)
export default LocationFinderSearchContainer
最佳答案
我认为你的第一直觉应该是将状态中的值映射到组件 Prop ,如下所示:
const getInputValue = state =>
state.locationFinderReducer.locationFinder.ui.inputValue
const mapStateToProps = state => ({
inputValue: getInputValue(state),
})
现在您在组件属性中已经有了 inputValue,问题是如何在您的调度函数中使用?
为此,我鼓励您将即时事件处理(preventDefault 和 target.value)放入组件内。这使得mapDispatchToProps对象变得更加容易,将事件处理封装在您的组件中,并最终解决了不使用getState()的问题。
你的mapDispatchToProps变成:
import { getLocations, setSearchValue } from './locationFinderSearchActions'
const mapDispatchToProps = {
getLocations,
setSearchValue,
}
LocationFinderSearch 组件现在必须处理事件并可以访问 this.props.inputValue 中的 inputValue:
class LocationFinderSearch extends React.Component {
...
onLocationSearchClick = (e) => {
const { getLocations, inputValue } = this.props
e.preventDefault()
getLocations(inputValue)
}
onLocationInputChange = (e) => {
const value = e.target.value
const { setSearchValue } = this.props
e.preventDefault()
setSearchValue(value)
}
...
}
希望这个回答对你有帮助。
关于javascript - 在 redux 容器中使用 store.getState() 是否正确?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43436894/