'Cannot read property 'map' of undefin

2019-01-15 22:43发布

问题:

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

回答1:

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