IT이야기

환원기. 상태 값을 환원기에 전달

cyworld 2022. 3. 12. 10:25
반응형

환원기. 상태 값을 환원기에 전달

내 앱에 Redex를 구현하려고 해.그래서 액션, 환원기, 가게 등을 만들었는데...그리고 이제 상태를 환원기에 전달하고 이 파라미터의 값(부울)을 변경해야 한다.내가 뭘 잘못하고 있는지 모르겠어.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;

환원기 지수.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,
   };
}

사용할 때redux그리고 그 값을 읽는다.store당신은 그것을 사용할 필요가 있다.props당신의 구성 요소 안에.간단히 말해서 당신은 a를 가져서는 안 된다.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에서는 combinateReducers를 사용하는 경우 해당 환원기에서 열린 값에 액세스해야 함

그래서 만약 너가 사용한다면combineReducer맘에 들다

const reducers = combineReducer({
   checkPassword:checkpasswordReducer
})

당신은 당신의 것을 사용할 필요가 있다.mapStateToProps처럼 기능하다.

function mapStateToProps(state) {
   return {
       open: state.checkPassword.open,
   };
}

참조URL: https://stackoverflow.com/questions/48517565/redux-pass-state-value-to-reducer

반응형