gpt4 book ai didi

javascript - 还原。将状态值传递给 reducer

转载 作者:行者123 更新时间:2023-11-29 20:57:34 27 4
gpt4 key购买 nike

我正在尝试在我的应用中实现 Redux。所以,我创建了 action、reducer、store 等……现在我必须将状态传递给 reducer 并更改此参数( bool 值)的值。我不知道我做错了什么。单击按钮后会触发 reducer 中的 alert,但 dialog 不会关闭。知道如何更改 open 的值吗?

Action

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;

reducer

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
});

最佳答案

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,
};
}

关于javascript - 还原。将状态值传递给 reducer ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48517565/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com