Компонент созданный в 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">* </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">* </span>
Обязательное поле
</div>
)}
{!this.props.necessarily && this.props.helpText}
</small>
</div>
)}
</div>
);
}
}
export default InputView;
Подскажите, пожалуйста, в чем может быть проблема. И как грамотно ее устранить.