我正在尝试使用react-redux发送一个动作。我已经看了几个教程并阅读了文档,但是,我仍然不确定我做错了什么。
以下是一些代码:
Container.js
import React from 'react';
import {connect} from 'react-redux';
import * as Actions from '../../../actions'
import { bindActionCreators } from 'redux'
class Searchbar extends React.Component {
// some constructor here
// some methods
onClickAction(){
let {rememberUserQuery} = this.props.actions
console.log(this.props.userQuery) //empty as expected
rememberUserQuery(someInputDeclaredInsideTheMethod)
console.log(this.props.userQuery) //still empty instead of being updated
};
// some rendor
}
}
function mapStateToProps(store) {
let {userQuery} = store.landingPgReducer;
return {userQuery}
}
function mapDispatchToProps(dispatch) {
return {
actions: bindActionCreators(Actions, dispatch)
}
}
export default connect(mapStateToProps, mapDispatchToProps)(Searchbar)
Reducers.js
import {
REMEMBER_USER_QUERY
} from '../actions'
// Reducer to keep track of which form should be shown
export function landingPgReducer(state = {userQuery:''}, action) {
switch (action.type) {
case REMEMBER_USER_QUERY:
console.log(state) //the reducer gets called and has blank state as expected
console.log(action) //the reducer is called with inputs as expected
return Object.assign({}, state,
action.userQuery
)
default:
return state
}
}
Actions.js
export const REMEMBER_USER_QUERY = 'REMEMBER_USER_QUERY'
export function rememberUserQuery(userQuery) {
console.log('rememberUserQuery',userQuery) //never getting to that console.log
return {
type: REMEMBER_USER_QUERY,
userQuery
}
}
P.S。我在另一个文件中组合了reducers并创建了一个我要连接的商店。
更新:我正在尝试更改全局状态,以便在我使用动作调用reducer后立即使用this.props.history.push(“/ reports”)在我导航的另一个组件中进行渲染。在这个其他组件中,全局状态没有改变,'userQuery'的值仍然是'',因为代码中的console.logs正在显示。
答案 0 :(得分:2)
尝试修改您在reducer的return语句中传递给 Object.assign()的对象到以下内容:
Reducers.js
import { REMEMBER_USER_QUERY } from '../actions'
// Reducer to keep track of which form should be shown
export function landingPgReducer(state = { userQuery: '' }, action) {
switch (action.type) {
case REMEMBER_USER_QUERY:
console.log(state) // the reducer gets called and has blank state as expected
console.log(action) // the reducer is called with inputs as expected
return Object.assign({}, state, {
userQuery: action.userQuery
})
default:
return state
}
}
如果 action.userQuery 只包含来自用户输入的字符串,那么您将返回原始状态,因为您当前只是将字符串传递给 Object.assign()何时应该传递具有要覆盖的属性的对象。
答案 1 :(得分:0)
如下所示更改您的减速器。如果您的' action.userQuery'返回对象使用
return { ...state, action.userQuery }
否则
return {...state, userQuery: action.userQuery }
减速
import {
REMEMBER_USER_QUERY
} from '../actions'
// Reducer to keep track of which form should be shown
export function landingPgReducer(state = {userQuery:''}, action) {
switch (action.type) {
case REMEMBER_USER_QUERY:
console.log(state) //the reducer gets called and has blank state as expected
console.log(action) //the reducer is called with inputs as expected
return {...state,
userQuery: action.userQuery
}
default:
return state
}
}