简体   繁体   中英

access redux state to validate

I have a validation function that is in a seperate file outside of my component and I want to be able to access my redux store state to check if a value is valid or not but I am not able to access this state.

I have tried to access the store state by importing it into my validation.js file 'import store from '../../client' but this doesn't work

How can I access store state in validation.js or is there a better way to handle validations like this with react/redux?

client.jsx

import "@babel/polyfill";

import React from 'react';
import ReactDOM from 'react-dom';

import { createStore, applyMiddleware, compose } from 'redux';
import { composeWithDevTools } from 'redux-devtools-extension';
import { Provider } from 'react-redux';
import thunkMiddleware from 'redux-thunk';
// import {registerObserver} from 'react-perf-devtool'
import $ from 'jquery';

import Layout from './components/Layout/Layout.jsx';
import './styles.js'

import configuratorReducer from './reducer/reducer.js';
import configuratorHandler from './handler/handler.js';
import configuratorInit    from './handler/init.js';

import getInitState from './init/initState.js';

const composeEnhancers =
  typeof window === 'object' &&
  window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ ?
    window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__({
      maxAge: 500,
    }) : compose;

    const enhancer = composeEnhancers(
      applyMiddleware(thunkMiddleware),
      // other store enhancers if any
    );

export const store = createStore(
  configuratorReducer,
  getInitState(),
  enhancer
);


configuratorInit(store);
store.subscribe(() => configuratorHandler.handle(store));

$(document).ready( () => {

  const app = document.getElementById('app');

  ReactDOM.render(
    <Provider store={store}>
      <Layout />
    </Provider>
    , app
  );

});

addToCart.jsx

 class AddToCart extends React.Component {
     render() {
         return(
               <Wrap
        plissee={plissee}
        rollo={rollo}
        lamellen={lamellen}
        holzJalousie={holzJalousie}
        disabled={!this.props.isValid}
      >
         )
     }
 }

const mapStateToProps = (state) => {
  return {
    amount: state.model.amount,
    designation: {
      ...mapDesignationName(state.model.designation.alias),
      alias: state.model.designation.alias
    },
    isValid: configuratorIsValid(state),
    adding: state.model.cart.loading,
    price: state.model.price,
  };
};

const mapDispatchToProps = (dispatch) => {
  return bindActionCreators({
    ...addToCartActions,
  }, dispatch);
};

export default connect(mapStateToProps, mapDispatchToProps)(AddToCart);

validation.jsx

   export const operationLengthisValid = (state) => {
  return state.model.operationLength.value ? state.model.operationLength.isValid : null;
};

export const operationMotorPositionIsValid = (state) => {
  return state.model.operationMotorPosition.value ? state.model.operationMotorPosition.isValid : null;
};

export const operationHandlingIsValid = (state) => {
  return state.model.operationHandling.value ? state.model.operationHandling.isValid : null;
};

export const operationOpeningDirectionIsValid = (state) => {
  return state.model.operationOpeningDirection.value ? state.model.operationOpeningDirection.isValid : null;
};

export const configuratorIsValid = (state) => {
  const validations = [windowShapeIsValid, profileColorIsValid, operationTypeIsValid, dimensionIsValid, clothIsValid, fasteningIsValid];
  // rollo
  if (state.model.designation.id === 4) {
    validations.push(chainColorIsValid);
  }
  // lamellen
  if (state.model.designation.id === 5 && state.model.operationType.value === 'Kette und Zugschnur') {
    validations.push(operationLengthisValid,  operationOpeningDirectionIsValid, operationChildProofIsValid)
  }
  else if ((state.model.designation.id === 5 && state.model.operationType.value === 'Funkmotor')) {
    validations.push(operationMotorPositionIsValid, operationHandlingIsValid, operationOpeningDirectionIsValid)
  }


  return !!validations.reduce((prev, curr) => prev && curr(state), true);

The code you provided should work. The way you access the store when working with redux is, just as you did, by connect ing the component to the store, and calling methods if required.

I would note that, logic like that, should not be called as part of a component life-cycle. React (flux) urges you to have components that reflect state, not mutate it.

I would recommend instead placing the logic as part of a reducer. Whenever that state change, re-trigger the validation logic, and set a valid state on the store, and bind your component to it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM