Situation 我有一个使用redux的reactjs应用程序 . 我将'onChange'回调函数从容器传递给表示组件,该组件在键入其中一个文本字段时调度操作以更改redux状态 .
Problem 表示组件在表示组件安装时从redux状态成功呈现文本字段的正确值,但在键入字段时不会更新 . 如果我在容器中记录传递给 mapStateToProps
中的表示组件的props,我可以看到onChange函数正确地调度到存储,并且正在正确更新redux状态 . 但是当发生这种情况时,表示组件不会重新呈现,因此在文本字段中键入不会更新视图(键入什么都不做) .
formConnector
import { connect } from 'react-redux'
import Form from '../components/Form'
import { changeElementValue } from '../actions/actions'
const mapStateToProps = (state) => {
//e.g. state.elements = [{id:"email", value:"foo@bar.com"}]
let props = {
elements: state.elements,
}
//state and props.elements.{id}.value changes successfully when I
//type in one of the input fields, but
//the the Form component is not re-rendered
console.log(props)
return props
}
const mapDispatchToProps = (dispatch) => {
return {
onElementChange: (id, value) => {
dispatch(changeElementValue(id, value))
},
}
}
export default connect(mapStateToProps, mapDispatchToProps)(Form)
Form reducer
function formReducer(state = initialState, action = null) {
switch(action.type) {
case types.CHANGE_ELEMENT_VALUE:
let newState = Object.assign({}, state)
newState.elements[action.id].value = action.value
return newState
default:
return state;
}
}
actions
import * as types from './actionTypes'
export function changeElementValue(id, value) {
return { type: types.CHANGE_ELEMENT_VALUE, id, value }
}
1 回答
正如评论中所讨论的,这是由于状态突变 .
尝试更改您的reducer代码,如下所示:
或者更优雅: