Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
618 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 Answer

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...