redux: error when use redux @connect and this.context.router

I want to use it like this:


@connect(state => state)
class MessageComposer extends Component {

  componentWillMount() {
    // send login action
    const { dispatch } = this.props;
    dispatch(checkLogin(this.context.router));
  }

  render() {
    return (
      <div>
        <h1>MessageComposer</h1>
        <Link to='/login' >GO!</Link>
      </div>
    );
  }
}

MessageComposer.contextTypes = {
  router: React.PropTypes.object,
};

export default MessageComposer;

but it would give me some error like this

Uncaught Error: Invariant Violation: Could not find "store" in either the context or props of "Connect(MessageComposer)". Either wrap the root component in a <Provider>, or explicitly pass "store" as a prop to "Connect(MessageComposer)".

after I remove the decorator and change it like this

export default connect(state => state)(MessageComposer);

it would work

if i remove router context declare,it would work too

ps:

    "react-router": "^1.0.0-beta3",
    "react-redux": "^0.8.0",
    "redux": "^1.0.1",

About this issue

  • Original URL
  • State: closed
  • Created 9 years ago
  • Reactions: 1
  • Comments: 15 (7 by maintainers)

Most upvoted comments

My advice today is don’t use decorators at all. They are too easy to break with Babel 6, and they are not even an official feature in it. For example, specifying plugins in a different order can cause decorators to work incorrectly with static properties in Babel 6, which is likely the issue you are experiencing.

Until decorators are officially supported by Babel and the plugin ordering issues are solved, just avoid them:

class Root extends Component {
    static contextTypes = {
        router: React.PropTypes.object,
    }        
}

export default connect(state => state)(Root)

Either use ES7 proposal syntax both for properties and decorators (dangerous: subject to change), or just use ES6.

@connect(...)
class Stuff {} 

// WON'T WORK
Stuff.contextTypes = {
  router: React.PropTypes.object,
};

does not work because you’re assigning contextTypes to the wrapped component returned by connect. It’s like doing this:

class Stuff {}
Stuff = connect(...)(Stuff);

// WON'T WORK
Stuff.contextTypes = {
  router: React.PropTypes.object,
};

You can declare contextTypes as static class prop like this:

class MessageComposer extends Component {
  static contextTypes = {
    router: React.PropTypes.object,
  }
  //...
}