Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
612 views
in Technique[技术] by (71.8m points)

reactjs - 'Cannot read property 'map' of undefined' when using connect with mapStateToProps

I am trying to display my state (users) in my react/redux functional component:

const Dumb = ({ users }) => {
  console.log('users', users)
  return (
    <div>
      <ul>
        {users.map(user => <li>user</li>)}
      </ul>
    </div>
  )
}

const data = state => ({
  users: state
})


connect(data, null)(Dumb)

Dumb is used in a container component. The users.map statement has an issue but I thought that the data was injected through the connect statement? the reducer has an initial state with 1 name in it:

const users = (state = ['Jack'], action) => {
  switch (action.type) {
    case 'RECEIVED_DATA':
      return action.data

    default:
      return state
  }
}

CodeSandbox

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You aren't using the connected component while rendering and hence the props aren't available in the component

const ConnectedDumb = connect(
  data,
  null
)(Dumb);

class Container extends React.Component {
  render() {
    return (
      <div>
        <ConnectedDumb />
      </div>
    );
  }
}

Working demo


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...