Я реализовал очень простые вкладки на 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 кода? Что мне нужно изменить в моем коде?