我正在尝试将Redux应用到我的应用程序中。所以,我创建了action,reducer,store等...现在我必须将状态传递给reducer并更改此参数的值(boolean)。我不知道我做错了什么。在单击按钮后触发reducer中的alert
,但dialog
未关闭。知道如何改变open
的价值吗?
动作
export const checkPassword = () => ({
type: "CHECK_PASSWORD"
});
组件
const mapDispatchToProps = dispatch => {
return {
checkPassword: () => dispatch({type: 'CHECK_PASSWORD'})
};}
function mapStateToProps(state, open) {
return {
open: state.open,
};}
class StartDialog extends Component {
constructor(props) {
super(props);
this.state = { open: true };
}
render() {
const actions = [ <FlatButton label="Submit" onClick={this.props.checkPassword} /> ];
return (
<Dialog title="Welcome to the React App!" actions={actions} open={this.state.open} ></Dialog>
);}}
const StartForm = connect(mapStateToProps, mapDispatchToProps)(StartDialog);
export default StartForm;
减速
import { CHECK_PASSWORD } from "../constants/action-types";
const initialState = {
open: true
};
const checkpasswordReducer = (state = initialState, action) => {
switch (action.type) {
case CHECK_PASSWORD:
alert('action!')
return {...state, open: false};
default:
return state;
}};
export default checkpasswordReducer;
存储
import { createStore } from "redux";
import rootReducer from "../reducers/index";
const store = createStore(
rootReducer,
window.__REDUX_DEVTOOLS_EXTENSION__ &&
window.__REDUX_DEVTOOLS_EXTENSION__()
);
export default store;
Reducer index.js
import { combineReducers } from "redux";
import checkpasswordReducer from "./checkpasswordReducer";
export default combineReducers({ checkPassword: checkpasswordReducer
});
答案 0 :(得分:1)
当您使用redux
并阅读store
中的值时,您需要在组件中使用props
。简而言之,您不应该从state
直接导出props
。将您的组件更改为下面,它应该工作
class StartDialog extends Component {
render() {
const actions = [ <FlatButton label="Submit" onClick={this.props.checkPassword} /> ];
return (
<Dialog title="Welcome to the React App!" actions={actions} open={this.props.open} ></Dialog>
);
}
}
同样在mapStateToProps中你需要正确访问状态,如果你使用的是combineReducers,你需要从相应的reducer访问open值
因此,如果您使用combineReducer
之类的
const reducers = combineReducer({
checkPassword:checkpasswordReducer
})
您需要使用mapStateToProps
功能
function mapStateToProps(state) {
return {
open: state.checkPassword.open,
};
}
答案 1 :(得分:1)
open
位于props
而不是state
将渲染更改为此
<Dialog title="Welcome to the React App!" actions={actions} open={this.props.open} ></Dialog>
同样在mapStateToProps
函数open
中的值将在状态对象中,因此您不需要函数中的第二个参数
function mapStateToProps(state) {
return {
open: state.checkPassword.open,
};
}