0

Компонент созданный в Redux дублирует состояния на другие экземпляры этого компонента.

Я написал неплохой генератор Input-ов с использованием Redux. Все работало ровно до того момента, как я не начал использовать донный генератор в своем проекте. Я создал 2 CustomInput. Один для логина, другой для пароля. В начале все отображается нормально, но при обновлении одного поля текущее состояние распространяется сразу на оба CustomInput.

<Container className="d-flex align-items-center" style={{height: "100vh"}}>
     <Jumbotron className="m-2 w-100">
          <CustomInput id="CustomInput1" label="Логин" 
                       type="email" necessarily={true}/>
          <CustomInput id="CustomInput2" label="Пароль" 
                       type="password" placeholder="Введите пароль" maxLength="50" />
     </Jumbotron>
</Container>

customInput.js - корневой файл

import {Provider} from 'react-redux'
import * as React from 'react'
import configureStore from './store'
import AppContainer from './containers'

const store = configureStore();

export default class CustomInput extends React.Component {

    render() {
        return (
            <Provider store={store}>
                <AppContainer {...this.props}/>
            </Provider>
        );
    }
}

store.js - создание хранилища и присоединение reducers

import { applyMiddleware, createStore, compose } from 'redux'
import { persistCombineReducers } from 'redux-persist'
import storage from 'redux-persist/es/storage'
import createSagaMiddleware from 'redux-saga'
import reducers from './reducers'

const config = {
    key: 'root',
    storage,
};

const reducer = persistCombineReducers(config, {
    reducers
});

const sagaMiddleware = createSagaMiddleware();

const composeCreateStore = () =>
    compose(applyMiddleware(sagaMiddleware))(
        createStore,
    );

const configureStore = port => {
    const finalCreateStore = composeCreateStore(port);
    const store = {
        ...finalCreateStore(reducer)
    };

    return store;
};

export default configureStore

containers.js - вызов connect...

    import {connect} from 'react-redux'
    import App from './components/App'
    import {getReducesState} from "./reducers";
    import {updateCounter, checkValid} from "./actions";

    const mapStateToProps = (state, ownProps) => {
        let reducersState = getReducesState(state);
        if (ownProps.label !== undefined) reducersState.label = ownProps.label;
        if (ownProps.placeholder !== undefined) reducersState.placeholder = ownProps.placeholder;
        if (ownProps.necessarily !== undefined) reducersState.necessarily = ownProps.necessarily;
        if (ownProps.type !== undefined) reducersState.type = ownProps.type;
        if (ownProps.typeView !== undefined) reducersState.typeView = ownProps.typeView;
        if (ownProps.helpText !== undefined) reducersState.helpText = ownProps.helpText;
        if (ownProps.maxLength !== undefined) reducersState.maxLength = ownProps.maxLength;
        if (ownProps.showNec !== undefined) reducersState.showNec = ownProps.showNec;

        return {
            label: reducersState.label,
            placeholder: reducersState.placeholder,
            necessarily: reducersState.necessarily,
            type: reducersState.type,
            typeView: reducersState.typeView,
            helpText: reducersState.helpText,
            currentLength: reducersState.currentLength,
            maxLength: reducersState.maxLength,
            validClass: reducersState.validClass,
            showNec: reducersState.showNec
        }
    };

    const mapDispatchToProps = dispatch => ({
        onChangeInput: event => {
            dispatch(
                updateCounter(event.target.value.length)
            );
            dispatch(
                checkValid(event.target.value)
            )
        }
    });

    const AppContainer = connect(mapStateToProps, mapDispatchToProps)(App);
    export default AppContainer

import {createReducer} from 'redux-create-reducer'
import {constants as C, const_type as CT, const_typeView as CTV} from './constants'

import validator from 'validator';


const initialState = {
    type: CT.TEXT,
    typeView: CTV.USUAL,
    currentLength: 0
};

switch (initialState.type) {
    case CT.EMAIL:
        initialState.placeholder = "email@example.ru";
        break;
    case CT.PHONE:
        initialState.placeholder = "+7 (999) 999-0000";
        break;
    case CT.URL:
        initialState.placeholder = "https://reference.example.net";
        break;
    case CT.PASS: {
        initialState.necessarily = true;
        break;
    }
    default:
        initialState.placeholder = "";
}

export default createReducer(initialState, {
    [C.UPD_COUNTER](state, action) {
        return {
            ...state,
            currentLength: action.payload.currentLength,
        }
    },
    [C.CHECK_VALID](state, action) {
        const value = action.payload.value;

        return checkValid(state, value);
    }
})

const checkValid = (state, value) => {
    switch (state.type) {
        case CT.URL: {
            if ((state.necessarily && validator.isURL(value) && value !== "") ||
                (!state.necessarily && (validator.isURL(value) || value === ""))) {
                return {
                    ...state,
                    value: value,
                    validClass: "is-valid",
                }
            } else {
                return {
                    ...state,
                    value: value,
                    validClass: "is-invalid",
                }
            }
        }
        case CT.EMAIL: {
            if ((state.necessarily && validator.isEmail(value) && value !== "") ||
                (!state.necessarily && (validator.isEmail(value) || value === ""))) {
                return {
                    ...state,
                    value: value,
                    validClass: "is-valid",
                }
            } else {
                return {
                    ...state,
                    value: value,
                    validClass: "is-invalid",
                }
            }
        }
        case CT.PHONE: {
            const re = new RegExp('^\\+7 \\((\\d{3})\\) (\\d{3})-(\\d{4})$');
            const formatPhone = value.replace(re, '$1$2$3');
            if ((state.necessarily && formatPhone.length === 10 && value.length !== 0) ||
                (!state.necessarily && (formatPhone.length === 10 || value.length === 0))) {
                return {
                    ...state,
                    value: formatPhone,
                    validClass: "is-valid",
                }
            } else {
                return {
                    ...state,
                    value: formatPhone,
                    validClass: "is-invalid",
                }
            }
        }
        case CT.TEXTAREA: {
            if ((state.necessarily && value.length !== 0) ||
                (!state.necessarily)) {
                return {
                    ...state,
                    value: value,
                    validClass: "is-valid",
                }
            } else {
                return {
                    ...state,
                    value: value,
                    validClass: "is-invalid",
                }
            }
        }
        case CT.PASS: {
            if (value.length >= 6) {
                return {
                    ...state,
                    value: value,
                    validClass: "is-valid",
                }
            } else {
                return {
                    ...state,
                    value: value,
                    validClass: "is-invalid",
                }
            }
        }
        default:
            return {
                ...state,
                value: value,
                validClass: "is-invalid",
            }
    }
};

export const getReducesState = (state) => state.reducers;

actions.js

import C from './constants'

export const updateCounter = function (length) {
    return {
        type: C.UPD_COUNTER,
        payload: {
            currentLength: length
        }
    }
};

export const checkValid = function (value) {
    return {
        type: C.CHECK_VALID,
        payload: {
            value: value
        }
    }
};

import * as React from "react"; import InputView from "./InputView";

components/App.js

export default class App extends React.Component {
    render() {
        return (
            <InputView {...this.props}/>
        )
    }
}

components/InputView.js

import * as React from 'react'
import {} from 'react-bootstrap';
import uniqid from 'uniqid'
import {const_type as CT, const_typeView as CTV} from '../constants'
import InputMask from 'react-input-mask';

class InputView extends React.Component {

    render() {
        let helpId = uniqid("customInput_helpId");
        const Id = uniqid("customInput_Id");
        let input = <input id={Id} type={this.props.type} className={"form-control " + this.props.validClass}
                           aria-describedby={helpId}
                           placeholder={this.props.placeholder}
                           aria-label={this.props.label}
                           onChange={this.props.onChangeInput} maxLength={this.props.maxLength}/>;
        if (this.props.type === CT.TEXTAREA) {
            input = <textarea id={Id} className={"form-control " + this.props.validClass}
                              aria-describedby={helpId}
                              placeholder={this.props.placeholder}
                              aria-label={this.props.label} rows={this.props.rows}
                              onChange={this.props.onChangeInput} maxLength={this.props.maxLength}/>;
        }
        if (this.props.type === CT.PHONE) {
            input = <InputMask type="tel" className={"form-control " + this.props.validClass}
                               aria-describedby={helpId}
                               placeholder={this.props.placeholder}
                               aria-label={this.props.label}
                               onChange={this.props.onChangeInput}
                               mask="+7 (999) 999-9999" maskChar=" "/>;
        }

        return (
            <div>
                {this.props.typeView === CTV.USUAL && (
                    <div className="form-group">
                        {this.props.label && <label htmlFor={Id}>
                            {this.props.necessarily && this.props.showNec && (
                                <span className="text-danger">*&nbsp;</span>
                            )}
                            {this.props.label}
                        </label>}
                        {input}
                        {this.props.maxLength && this.props.type !== CT.PHONE && (
                            <small className="form-text text-muted float-right">
                                {this.props.currentLength} / {this.props.maxLength}
                            </small>
                        )}
                        {this.props.helpText && (
                            <small id={helpId} className="form-text text-muted">
                                {this.props.helpText}
                            </small>
                        )}
                    </div>
                )}
                {this.props.typeView === CTV.SHORT && (
                    <div>
                        <div className="input-group">
                            <div className="input-group-prepend">
                                {this.props.label && (
                                    <span className="input-group-text" id="basic-addon1">{this.props.label}</span>
                                )}</div>
                            {input}
                        </div>
                        {this.props.maxLength && this.props.type !== CT.PHONE && (
                            <small className="form-text text-muted float-right">
                                {this.props.currentLength} / {this.props.maxLength}
                            </small>
                        )}
                        <small id={helpId} className="form-text text-muted mb-2">
                            {this.props.necessarily && this.props.showNec && (
                                <div>
                                    <span className="text-danger">*&nbsp;</span>
                                    Обязательное поле
                                </div>
                            )}
                            {!this.props.necessarily && this.props.helpText}
                        </small>
                    </div>
                )}
            </div>
        );
    }
}

export default InputView;

Подскажите, пожалуйста, в чем может быть проблема. И как грамотно ее устранить.

2
  • ничётакойгенератор! нужно побольше картинок, чтобы все заценили какой генератор у вас получился!!!! Больше сказать нечего, кода мало.
    – user220409
    18 фев 2019 в 8:47
  • компоненты -это реакт а не redux - поправьте название и я бы не увязывал простой контейнер с redux. лучше думаю state тут заиспользовать более логично 18 фев 2019 в 9:31

1 ответ 1

1

Как подсказал Сергей Петрашко в комментарии к вопросу:

я бы не увязывал простой контейнер с redux. лучше думаю state тут заиспользовать более логично

я переписал все без Redux и оно в принципе работает. И кода меньше.

import * as React from 'react'
import {} from 'react-bootstrap';
import uniqid from 'uniqid'
import InputMask from 'react-input-mask'
import {const_type as CT, const_typeView as CTV} from "./constants";
import validator from "validator";

export default class CustomInput extends React.Component {

    constructor(props) {
        super(props);

        this.state = {
            type: props.type !== undefined ? props.type : CT.TEXT,
            typeView: props.typeView !== undefined ? props.typeView : CTV.USUAL,
            label: props.label,
            placeholder: props.placeholder !== undefined ? props.placeholder : "",
            maxLength: props.maxLength,
            currentLength: 0,
            necessarily: props.necessarily,
            showNec: props.showNec,
            helpText: props.helpText,
            validClass: "",
            onChange: props.onChange
        };

        switch (props.type) {
            case CT.EMAIL:
                this.state.placeholder = "email@example.ru";
                break;
            case CT.PHONE:
                this.state.placeholder = "+7 (999) 999-0000";
                break;
            case CT.URL:
                this.state.placeholder = "https://reference.example.net";
                break;
            case CT.PASS: {
                this.state.necessarily = true;
                break;
            }
        }

        this.onChangeInput = this.onChangeInput.bind(this);
    }

    onChangeInput(e) {
        const value = e.target.value;
        this.setState({
            value: value,
            currentLength: value.length
        }, () => {
            if (checkValid(this.state, value)) {
                this.setState({validClass: "is-valid"})
            } else {
                this.setState({validClass: "is-invalid"})
            }
        });
        if(this.state.onChange!==undefined){
            this.state.onChange(e);
        }
    }

    render() {
        let helpId = uniqid("customInput_helpId");
        const Id = uniqid("customInput_Id");
        let input = <input id={Id} type={this.state.type} className={"form-control " + this.state.validClass}
                           aria-describedby={helpId}
                           placeholder={this.state.placeholder}
                           aria-label={this.state.label}
                           onChange={this.onChangeInput} maxLength={this.state.maxLength}/>;
        if (this.state.type === CT.TEXTAREA) {
            input = <textarea id={Id} className={"form-control " + this.state.validClass}
                              aria-describedby={helpId}
                              placeholder={this.state.placeholder}
                              aria-label={this.state.label} rows={this.state.rows}
                              onChange={this.onChangeInput} maxLength={this.state.maxLength}/>;
        }
        if (this.state.type === CT.PHONE) {
            input = <InputMask type="tel" className={"form-control " + this.state.validClass}
                               aria-describedby={helpId}
                               placeholder={this.state.placeholder}
                               aria-label={this.state.label}
                               onChange={this.onChangeInput}
                               mask="+7 (999) 999-9999" maskChar=" "/>;
        }

        return (
            <div>
                {this.state.typeView === CTV.USUAL && (
                    <div className="form-group">
                        {this.state.label && <label htmlFor={Id}>
                            {this.state.necessarily && this.state.showNec && (
                                <span className="text-danger">*&nbsp;</span>
                            )}
                            {this.state.label}
                        </label>}
                        {input}
                        {this.state.maxLength && this.state.type !== CT.PHONE && (
                            <small className="form-text text-muted float-right">
                                {this.state.currentLength} / {this.state.maxLength}
                            </small>
                        )}
                        {this.state.helpText && (
                            <small id={helpId} className="form-text text-muted">
                                {this.state.helpText}
                            </small>
                        )}
                    </div>
                )}
                {this.state.typeView === CTV.SHORT && (
                    <div>
                        <div className="input-group">
                            <div className="input-group-prepend">
                                {this.state.label && (
                                    <span className="input-group-text" id="basic-addon1">{this.state.label}</span>
                                )}</div>
                            {input}
                        </div>
                        {this.state.maxLength && this.state.type !== CT.PHONE && (
                            <small className="form-text text-muted float-right">
                                {this.state.currentLength} / {this.state.maxLength}
                            </small>
                        )}
                        <small id={helpId} className="form-text text-muted mb-2">
                            {this.state.necessarily && this.state.showNec && (
                                <div>
                                    <span className="text-danger">*&nbsp;</span>
                                    Обязательное поле
                                </div>
                            )}
                            {!this.state.necessarily && this.state.helpText}
                        </small>
                    </div>
                )}
            </div>
        );
    }
}

const checkValid = (state, value) => {
    switch (state.type) {
        case CT.URL: {
            return ((state.necessarily && validator.isURL(value) && value !== "") ||
                (!state.necessarily && (validator.isURL(value) || value === "")));
        }
        case CT.EMAIL: {
            return ((state.necessarily && validator.isEmail(value) && value !== "") ||
                (!state.necessarily && (validator.isEmail(value) || value === "")));
        }
        case CT.PHONE: {
            const re = new RegExp('^\\+7 \\((\\d{3})\\) (\\d{3})-(\\d{4})$');
            const formatPhone = value.replace(re, '$1$2$3');
            return ((state.necessarily && formatPhone.length === 10 && value.length !== 0) ||
                (!state.necessarily && (formatPhone.length === 10 || value.length === 0)));
        }
        case CT.TEXTAREA: {
            return ((state.necessarily && value.length !== 0) ||
                (!state.necessarily));
        }
        case CT.PASS: {
            return value.length >= 6;
        }
        default:
            return false;
    }
};
  • Однако все равно хотелось бы узнать как с помощью Redux правильно создавать компоненты, которые в последствии можно будет использовать много раз?
  • Неужели Redux не предназначен для подобного совсем?
  • А если Redux не предназначен для таких вещей, то в каких ситуациях использовать обычный state, а в каких Redux?

Ваш ответ

Нажимая на кнопку «Отправить ответ», вы соглашаетесь с нашими пользовательским соглашением, политикой конфиденциальности и политикой о куки

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.