简体   繁体   English

无法在React-redux中使用Connect访问存储

[英]Cannot access store with connect in React-redux

I am using React in my application. 我在我的应用程序中使用React。 I am using connect to access the store, Briefly I have this code: 我正在使用connect来访问商店,简而言之,我有以下代码:

class MyComponent extends Component{
   constructor(props){
        super(props)
    }

    render(){
      let components = this.props.components;
      if(components.indexOf("SomeString")){
           //some stuffs
      }
        return (
            <SomeElement/>
        )
    }
}


const mapStateToProps = state => {
    return {
        components: state.someReducer.components
    }
}

export default connect(mapStateToProps)(MyComponent)

Components is an array of strings, if I print with console.log(this.props.components) inside the render function, the I am able to see the array in the browser console. 组件是一个字符串数组,如果我在render函数中使用console.log(this.props.components)打印,则可以在浏览器控制台中看到该数组。 However, if I try to find a value inside that array using indexOf then I get this error: 但是,如果我尝试使用indexOf在该数组中找到一个值,则会收到此错误:

TypeError: components is undefined

So, What am I missing? 所以,我想念什么? I tried many things without result 我尝试了很多事情都没有结果

At first cycle, this.props.components is undefined. 在第一个循环中, this.props.components是未定义的。 You can bypass it using 您可以使用

render(){
      if(this.props.components) {
      let components = this.props.components;
      if(components!=null || components!=undefined){ //this will check if components is null or undefined
        if(components.indexOf("SomeString")){
           //some stuffs
        }}
          return (
            <SomeElement/>
          )
    }

You need to check for the this.props.components like so: 您需要像这样检查this.props.components

render(){
      if(this.props.components) {
        let components = this.props.components;
        if(components.indexOf("SomeString")){
           //some stuffs
        }
        return (
           <SomeElement/>
        )
      } else {
           return(<div>Loading...</div>)
      }
 }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM