Error: TypeError: Cannot read property 'map' of undefined in React-Redux

Error: TypeError: Cannot read property 'map' of undefined in React-Redux

我正在使用 axios 从 https://jsonplaceholder.typicode.com/users 进行一些简单的获取,我正在使用 redux 来存储应用程序的状态。从 url 上传,我想在下拉列表中获取所有名称。但是从 2 天开始给我这个错误:

TypeError: Cannot read property 'map' of undefined.

现在我将在下面提供一些代码片段,如果你以前看过的话。

动作到这里,我觉得还可以。

export const getAuthors = () => {
 return (dispatch) => {
axios.get('https://jsonplaceholder.typicode.com/users')
  .then((response) => {
    dispatch({
      type: GET_AUTHORS,
      payload: response.data
    })
  })
  .catch(e => console.log(e))
 }}

这里是 reducer,我认为这里是错误:

export default (state = initialState, action) => {
console.log("ACTION", action.payload);
switch (action.type) {
    case GET_AUTHORS:
        return {...state, authors: action.payload}
    default:
        return state;
}
}

这是显示错误的函数组件:

const AddPostModal = ({authors, authorName}) => {
  return(
      <select
          value={authorName}
          onChange={handleChangeAuthor}
          {
             authors.map((author, index) => {
                return (
                   <option key={index}> {author.name} </option>
                )
             })
      </select>
  )
}
export default AddPostModal;

下面我们有 class 组件:

import { getAuthors} from '../../actions/PostActions';
class Post extends React.Component{
    constructor(props) {
    super(props);
    this.state = {
      authorName: ''
    }
   }
   render() {
     return(
       <AddPostModal
         authors={this.props.author}
         authorName={this.state.authorName}
       />
     )
   }
  }
   const mapStateToProps = (state) => {
     return {
       authors: state.authorName.authors
     };
   }

   const mapDispatchToProps = (dispatch) => (bindActionCreators({
     getAuthors: getAuthors,
   }, dispatch))

   export default connect(mapStateToProps, mapDispatchToProps)(Post);

如果有人有解决方案,请告诉我,因为你会拯救我的一天。非常感谢您。

API returns 结果是异步的,所以您可以先简单地 null 检查 authors。从技术上讲,.map() 只能在数组上调用,null 会抛出您在解决方案中看到的错误。

尝试以下操作:

<select value={authorName}
        onChange={handleChangeAuthor}>
          {
             authors && authors.map((author, index) => {
                return <option key={index}> {author.name} </option>
          })
</select>

希望对您有所帮助!

在您的 Post 组件中,this.props.author 可以是 nullundefined,具体视情况而定。所以我宁愿只在 this.props.author 不是 nullundefined 时调用 AddPostModal 因为 this.props.authorAddPostModal[=22 所必需的=]

Post 组件上:

const mapStateToProps = (state) => {
     return {
       authors: state.authorName.authors || []
     };
   }

首先,请确保您的 initialState.authors[]。其次确保 mapStateToProps 中的 state.authorsName 正确指向 authorName reducer 的状态。否则,它可能应该像 authors: state.authors.