Answer a question

I am trying with simple object reducer to display data in a component. But the state of that object is not getting upto the component. The code structure as below.

labels.js:

  export default function () {
    return [
    { id: 1, name: "Labels1"},
    { id: 2, name: "Labels2"}
    ]
}

allReducer(index):

import { combineReducers } from 'redux';
import labelsReducer from './labels';

const allReducers = combineReducers({
    labels: labelsReducer
});

export default allReducers;

store:

import { createStore } from 'redux';
import allReducers from './reducers/index'

function configureStore() {
    return createStore(allReducers);
}

export default configureStore;

APP

import React from 'react';
import './App.css';
import Labels from './components/Labels.jsx';

import { Provider } from "react-redux";
import configureStore from './store';

function App() {
  return (
    <Provider store={configureStore()}>
      <div className="App">
        <Labels />
      </div>
    </Provider>
  );
}

export default App;

Labels:

import React from 'react';
import { connect } from 'react-redux';

class Labels extends React.Component {
    labelsList() {
        this.props.labels.map((label) => {
            return (
                <li key={label.id}>{labels.name}</li>
            )
        })
    }

    render() {
        return(
            <label>{this.labelsList()}</label>
        )
    }
}

function mapStateToProps(state) {
    return (
        labels: state.labels
    )
}

export default connect(mapStateToProps)(Labels);

Why I am getting below error. What is the issue on connect state with reducer ./src/components/Labels.jsx Line 9:37: 'labels' is not defined no-undef Line 23:9: 'labels' is not defined no-undef

Answers

You need to use the connect function from react-redux. Import at the top:

import { connect } from 'react-redux'

And at the bottom of your component, do:

connect(mapStateToProps, mapDispatchToProps)(labelsList)

EDIT:

function mapStateToProps(state) {
    return (
        labels: state.labels
    )
}

should be:

function mapStateToProps(state) {
    return {
        labels: state.labels
    }
}

(note the curly brackets for returning the object, not standard parentheses)

and <li key={label.id}>{labels.name}</li> should be label.name. labels doesn't exist as a local variable in the scope.

Logo

React社区为您提供最前沿的新闻资讯和知识内容

更多推荐