@ArturPetrov

Какие ошибки я допустил при написании Redux кода? Что мне нужно изменить в моем коде?

Я реализовал очень простые вкладки на React.js.
Вы можете увидеть, как это работает в песочнице:
https://codesandbox.io/s/react-tabs-redux-example-36psr
И здесь напишу код:

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

const items = [{content:"London"}, {content:"Paris"}];

class Content extends React.Component {
    render(){
        return (
        <div>
        {this.props.content}
        </div>
        );
    }
}

class Tabs extends React.Component {
    state = {
        active: 0
    }

   open = (e) => {
       this.setState({active: +e.target.dataset.index})
   }
    
    render(){
        return(
        <div>
            {this.props.items.map((n, i)=>
            <button data-index={i} onClick={this.open}>{n.content}</button>
            )}
    
       {this.props.items[this.state.active] && <Content {...this.props.items[this.state.active]} />}
        </div>
        );
    }
}

ReactDOM.render(<Tabs items={items} />, document.getElementById("root"));

Но я начал изучать Redux и поэтому решил создать эти вкладки на Redux. Но, к сожалению, мои вкладки на Redux не работают.
Код в песочнице:
https://codesandbox.io/s/react-tabs-redux-example-ygg0f
И код здесь напишу:
import React from "react";
import ReactDOM from "react-dom";
import { Provider } from "react-redux";
import {createStore} from "redux";
import { combineReducers } from "redux";
import { connect } from "react-redux";

// action 
function changeTab (change){
    return{
        type: "CHANGE_TAB",
        change: change
    };
}

//Reducer
function reducer(state={someTab:{active: 0}},action){
    switch(action.type){
        case "CHANGE_TAB":
        return Object.assign({}, state, {
           change: action.change
        });
        default: 
            return state;
    }
}

// CombineReducer
const allReducers = combineReducers({
    oneReducer: reducer
});

// Tabs - main component
const items = [{content:"London"},{content:"Paris"}];

class Tabs extends React.Component {
    render(){
        return(
        <div>
            {this.props.items.map((n,i)=>
            <button data-index={i}  onClick={e => this.props.changeTab({this.props.someTab.active:+e.target.dataset.index})}>{n.content}</button>
            )}
            
            this.props.items[this.props.someTab.active] && <Content {...this.props.items[this.props.someTab.active]} />}
        </div>
        );
function mapStateToProps(state){
    return {
      onOneReducer: state.oneReducer
    };
}

function matchDispatchToProps (dispatch) {
  return {
     changeTab: () => dispatch(changeTab),
   };
}

connect(mapStateToProps,matchDispatchToProps)(Tabs);
    }
}

// Content - other component
class Content extends React.Component {
    render(){
        return (
          <div>
           {this.props.content}
          </div>
        );
    }
}


// index.js
const store = createStore(allReducers);

ReactDOM.render(
   <Provider>
    <Tabs items={items} />
   </Provider>,
document.getElementById("root")
);

Какие ошибки я допустил при написании Redux кода? Что мне нужно изменить в моем коде?
  • Вопрос задан
  • 288 просмотров
Решения вопроса 1
@curious-101
Frontend developer
1. с кавычками накосячил
2. не передал стор в провайдер
3. какая-то лютая дичь с логикой стора и переключением
4. В провайдер обернул незаконнекченный компонент
кароч, что-то примерно такое должно получится https://codesandbox.io/s/react-tabs-redux-example-63186
Ответ написан
Пригласить эксперта
Ответы на вопрос 1
0xD34F
@0xD34F Куратор тега React
Я реализовал очень простые вкладки на React.js.

Не вы. Или не реализовали. "Скопипастил" !== "реализовал".

на Redux не работают

Что неудивительно. Готового-то примера нет - приходится копипастить куски из разных мест, которые вы не способны сложить в хотя бы просто синтаксически корректный код. Спрашиваете, какие ошибки допустили? Ошибка ровно одна - пытаетесь освоить react/redux без знаний js. Впустую тратите своё время, так у вас ничего не получится. Забудьте про react, забудьте про redux, изучайте js.
Ответ написан
Комментировать
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Войти через центр авторизации
Похожие вопросы