Giter VIP home page Giter VIP logo

react-redux's People

Contributors

adispring avatar agraboso avatar andarist avatar aryaemami59 avatar chentsulin avatar dependabot[bot] avatar ellbee avatar eps1lon avatar esamattis avatar eskimojo14 avatar gaearon avatar gnoff avatar istarkov avatar jhollingworth avatar jimbolla avatar jspurlin avatar markerikson avatar martincik avatar methuselah96 avatar mpeyper avatar mrwolfz avatar msmolens avatar mynameisdu avatar nickmccurdy avatar oliverjash avatar phryneas avatar sveinpg avatar tgriesser avatar timdorr avatar wgao19 avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

react-redux's Issues

Dumb/smart component pattern and repaints

Using the dumb/smart components pattern, does it mean that all dumb components will be re-rendered when the "containers" receive a new state notification ? For example in the the todo example adding a todo to the list will re-render the whole app.

Are there any pattern to optimise repaints in a larger app ?

best place for create actions

Hi. I am using redux and react-redux bindings for it and have the problem with getting right state when component just mount. The problem is: I can't start action before first render:

class HomePage extends Component {
  ...
  componentWillMount() {
    this.props.fetchMovies({type: free, limit: 10});
  }

  render() {
     const { movies } = this.props;
     // right now movies.isFetching = false;
  }
}

export default connect(selectMovies, bindActions)(HomePage);

I want that at the first render I see that movies already fetching, how could I do this?

Upgrading to [email protected] produces `dispatch is not a function`

I was using [email protected] with no issues, then I upgraded to the full release and now I'm getting this error: dispatch is not a function. (In ‘dispatch(actionCreator.apply(undefined, arguments))’, ‘dispatch’ is undefined)

When I downgrade back to [email protected], it works fine and goes away. I have no idea what changed. Maybe it's a react-native issue?

These are my containers... I can provide more if needed. Right now it's pretty basic, mostly just following the examples.

// App.js
import React, { Component } from 'react-native'
import { createStore, applyMiddleware, combineReducers } from 'redux'
import { Provider } from 'react-redux/native'
import thunk from 'redux-thunk'

import * as reducers from '../reducers'
import VetoApp from './VetoApp'

const createStoreWithMiddleware = applyMiddleware(thunk)(createStore)
const reducer = combineReducers(reducers)
const store = createStoreWithMiddleware(reducer)

export default class App extends Component {
  render() {
    return (
      <Provider store={store}>
        {() => <VetoApp />}
      </Provider>
    )
  }
}
// VetoApp.js
import React, { Component } from 'react-native'
import { bindActionCreators } from 'redux'
import Main from '../components/Main'
import * as ViewActions from '../actions/view'
import { connect } from 'react-redux/native'

@connect(state => ({
  state: state.view
}))
export default class CounterApp extends Component {
  render() {
    const { state, dispatch } = this.props
    console.log(dispatch) // results in undefined
    return (
      <Main
        viewSettings={state}
        {...bindActionCreators(ViewActions, dispatch)}
      />
    )
  }
}

EDIT: now downgrading doesn't work. I reverted my app to the exact same state before and it doesn't work. dispatch is not a function. No idea what suddenly changed.

ES6 Failed propType

Hi, I'm using the connector to a ES6 class. I get my data but a warning on the propType. "Warning: Failed propType: Required prop data was not specified in Home. Check the render method of Router."

I tried enabling es7.classProperties and move to static propTypes = ... That got rid of the warning but I rather stay on ES6 and only the ES7 features that i really want (like es7.decorators). Any ideas?

@connect(state => ({
    data: state.info
}))
export default class Info extends React.Component {
    render() {
        return (
            <InfoComponent data={this.props.data}/>
        );
    }
}

Info.displayName = 'Info';
Info.propTypes = {
    data: React.PropTypes.object.isRequired
};

Maintain static functions

Could connect() check its wrapped component for static functions and add them to the returned component? For things like fetchData() and onEnter(). Seems like it would be pretty easy to go through the keys and check if typeof WrappedComponent[key] === 'function'.

Just a thought.

Render not called when dispatch

Hello

I am trying to port my project to Redux.
My components are react already. And I added
everything needed (or at least I think so) to
obey the redux framework.

But my React Component wont re-render even if I use
export default connect(state => state)(WorkspaceView)

The reducer gets called, the state is altred, but nothing happens.
When I force a render manually it works.

I uploaded my project here https://dl.dropboxusercontent.com/u/11300320/PTG.zip , and the component I am writing about is called Workspace view.
Just dload it, run npm install gulp and ./run.
It uses electron.io therefore the run command
Please help me !

Regards Carsten

Version 0.6.0 doesn't work with react-router

I'm having rather strange issue in my app. After upgrading to 0.6.0 transitions to routes stoped working. While url in browser is changing the page stays the same. With 1.0.0-alpha everything works fine.

null as the selector parameter to connect

Some components want to fire actions only and need not be connected to store state, i propose that connect accepts null as a first parameter ( default to () => ({}) ), it's not THAT important :P

Problems with context

I'm trying to build my own components on top of react-redux. I'm stuck with the following error:

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

My components need to have their own childContext. Mb I need somehow to merge childContext of my components with one from react-redux?

state change doesn't cause re-render of connected component

Hi,

I have the following behavior after upgrading to 0.5.0

  1. I changed the @provide to use Provider
  2. didn't change connect for now
@connect(state => ({
 todos: state.todos
}))

Now, when component is mounted it calls the action to load the initial state

  componentDidMount() {
    this.props.actions.listTodos();
  }

component is rendered with default props

I could see the action causes the state to be populated

API_TODOS_QUERY
  dispatching Object {type: "API_TODOS_QUERY", payload: Array[4]}
  next state Object {ui: Object, todos: Array[4]}

but there is no re-render. The new state is shown in the UI (rendered by the component) next time. that is if the same button/nav item is clicked again or navigate away and back to the same screen.

Let me know what else needed to help me with this issue.

ConnectedComponent

Is there a way to create a class which will be a base class for Smart Components, instead of using export default connect(select)(CounterContainer);?

So it would looks like:

export default CounterContainer extends ConnectedComponent {
  select(state) {
    return {
      counter: state.counter
    };
  }
  render() {
    const { dispatch, counter } = this.props;
    return (
      <Counter counter={counter}
               increment={() => dispatch(increment())} />
  );
}

I'm not sure, probably it is not possible to implement connector as a base class or that is not a right way of how it should be done in javascript.

connect(mapStateToProps) is executed with component props based on the previous state

Ok, this is really hard to explain so I've set up an example here:

https://github.com/epeli/redux-connect-demo

Build it and play with it with devtools console opened. You should see following errors:

Uncaught TypeError: Cannot read property 'foo' of undefined

This happens because the mapStateToProps of the Item component is called with component props based on the previous store state. The two states are not compatible anymore and it causes all kinds of errors.

I think the parent should render and update the props for the Item component before the mapStateToProps of the Item component can be executed.

Could not find "store" in either the context or props

I get a Could not find "store" in either the context or props error whenever I try to connect a component to Redux.

When I'm in the debug console I can see that state is defined on this and context but it has a value of undefined. Also, when I inspect createStore I get an object back with dispatch, getState, etc.

import { Provider } from 'react-redux';
import React from 'react';
import reducers from '../config/reducers';
import { createStore } from 'redux';
import routes from '../config/routes';

React.render(
  <Provider store={ createStore(reducers) }>
    { () => routes }
  </Provider>
, document.body);

Component

import React from 'react';

// components
import Footer from './_footer';
import Header from './_header';

// redux
import { connect } from 'react-redux';

import ClientSessionActionCreators from '../../actions/client-session-action-creators';

class ApplicationLayout extends React.Component {
  render() {
    return (
      <div>
        <Header />
        { this.props.children }
        <Footer />
      </div>
    );
  }
}

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

Suggestion: @connect's shouldComponentUpdate could be optional or opt-in

The @connect decorator, by default, appears to add a very aggressive shouldComponentUpdate hook to the decorated component. This is great if Redux and props are the only sources of statefulness in your app - but that's not always true and leads to some seriously confusing behavior with non-obvious workarounds when it's not.

This is a known issue, of course, with react-router 0.13, but I'm having the same issue with react-intl's IntlMixin, which adds localization data to context. And I get the feeling that this is going to keep happening as long as the React ecosystem is as fragmented as it is right now.

It would be really nice to just be able to throw an option on the @connected components that I know are impure (or, similar to React core's PureRenderMixin, throw an option on the ones I know are pure; there's certainly room for debate as to whether opt-in or opt-out is the right choice here).

Can't connect store with component without using require and jsx

Hi,

thanks for your awesome work. I use react, redux and react-redux for a small feature of my Ruby on Rails project. I don't use npm and require and thats why I use the browserified versions of these libs. I also use coffeescript and decided against using jsx.
I somehow can't manage to connect my store to my react component. The code looks like this

CustomQuizCreator = React.createClass
  render: ->
    # this.props is somehow empty

# this methods somehow never gets called
mapStateToProps = (state) ->
  lectures: state.lectures

ReactRedux.connect(mapStateToProps)(CustomQuizCreator)

lectures_reducer = (state=[], action) ->
  switch action.type
  # ...

custom_quiz_reducer = Redux.combineReducers
  lectures: lectures_reducer

store = Redux.createStore(custom_quiz_reducer)

React.render(
  React.createElement(ReactRedux.Provider, {store},
    -> React.createElement(CustomQuizCreator)
  ),
  $('#modal_custom_quiz')[0]
)

I hope you guys can help me to figure out what is wrong.

Thanks,

Johannes

About the LICENSE

Hi, Dan. I'm working around the project of connecting Redux and GraphQL. For now I'm feeling that it would be an alternative for react-redux. So I'm using some of your code in my project. There is no LICENSE in this repo, so I'm not sure if its ok. And how should I mention you in my repo? I'm just not competent with this license stuff.

Best way to determine state depending on prop(s)?

This is probably a stupid question, as I have a feeling I'm overlooking something obvious or doing something wrong. :)

Suppose we have a tree of files to explore, and we want to be able to provide an initial state based on the files/directories the user had opened when they were last using the app or possibly based on the project/workspace/whatever. So imagine we have this initial state serialized as follows:

const open = {
  'redux/src': true,
  'redux/examples': true,
  'redux/examples/counter': true,
  'redux/examples/counter/server.js': true
};

And then for each item in the tree (let's call it a Limb component), we want to provide props.isOpen based on a combination of the open state and the path prop which is specific to each Limb. And we also want to provide toggle prop (function) that updates both the open object and props.isOpen such that only the Limb being toggled is affected.

What's the best way to achieve this with redux and react-redux?

Issue with same props in shouldComponentUpdate

I'm having an issue with Redux, when I try to implement shouldComponentUpdate for a dumb component, this.props already holds the same value as nextProps. I read this was an issue linked with Flux architectures which I'm using Redux for, but I don't understand why this would happen. Is there any way around it?

Confusing documentation

Redux docs state:

[We] wrap the components we want to connect to Redux with the connect() function from react-redux. Try to only do this for a top-level component, or route handlers. While technically you can connect() any component in your app to Redux store, avoid doing this too deeply, because it will make the data flow harder to trace.

https://rackt.github.io/redux/docs/basics/UsageWithReact.html

But, in a seeming contradiction, react-redux README states:

Don’t do this! It kills any performance optimisations because TodoApp will rerender after every action.
It’s better to have more granular connect() on several components in your view hierarchy.

I'm not sure whose advice to follow!

Specifying root component as a function in React 0.14

The readme mentions that the child of Provider will no longer have to be specified as a function starting in React 0.14. I'm using 0.14 (beta 3) in a current project, but react-redux yells at me if I don't provide the child as a function.

Any chance of disabling this warning now that 0.14 is in beta? (Perhaps in a beta npm release, if you'd prefer?)

Thanks for your work on Redux!

can i wrap multi actionCreators into one props with name?

We can

Inject todoActionCreators as todoActions, and counterActionCreators as counterActions

Inject todoActionCreators and counterActionCreators together as actions

now.

can i Inject todoActionCreators as todoActions, and counterActionCreators as counterActions, and then together as actions?

{
  actions: {
    todoActions,
    counterActions,
  }
} 

Using `connect()` with `Immutable.Map` state object

My store is an Immutable.Map object, and I would like to pass it down my tree of React components. I suppose that in most cases I can get good performance by using something like PureRenderMixin (or ES2015 equivalent) when doing so.

I started out simple decorating my App class with @connect(state => state), and I got this error:

“Uncaught Error: Invariant Violation: mapStateToProps must return an object. Instead received Map {…”

I’m able to do something like @connect(state => {return {state};}), and then unwrap the object in App’s render(), but I get the sense that this is not an ideal solution.

Connector should use deepEqual

I have been hunting a bug that turns out to have been caused by the fact that Connector shallowly compares the current slice to the next. The diffs buried deep in a slice doesn't trigger updates in the connected components because of this. For example:

Before:

{
   MapReducer: {
      layers: []
   }
}

After:

{
   MapReducer: {
      layers: [{id: 1, name: 'my-layer'}]
   }
}

...no updates.

I know I can do @connect(state => state.MapReducer) but I also want the component to receive the state from other reducers. Any tips for me?

[feature-req] Actions on mount parameter

Would be nice to have a fourth optional parameter in connect with signature (props, boundActions) => that gets executed once the connected component mounts. It's a very common pattern to want to fetch data from an endpoint on component mounting and would be nice to push side effects into connector rather than the component itself.

[just ideas] - Option for dealing with deep component prop passing within Connected components

Apologies for polluting the issue list since it's not really an issue but I believe there is some interest in coming up with a workable solution that

a) Keeps the Smart/Dumb component divide clean & generally near the top of the component tree for a given part of the app domain AND
b) Avoid the hassle of passing @connect results down deep chains of children

I liked the Provide/connect pattern a lot so I generalized it in react-tunnel and starting playing with a patter like so

// in some Top level Component
<Provider store={mystore} /> //react-redux Provider
  {() => <App />}
</Provider>

// in a route handler
@connect(
  myStateMapper,
  (dispatch) => ({
    someActions: bindActionCreators(subsetOfMyActions, dispatch)
  })
)
export class ConnectedComponent...

// within ConnectedComponent's render()
<Provider someActions={this.props.someActions}> //react-tunnel Provider
  {() => <PageController />}
</Provider>

// deep within PageController's render tree
@inject(
  (provided) => ({
    specificActionIwant: someActions.specificActionIwant
  })
)
export class DeepComponent...

//within DeepComponent's lifecycle methods
...
this.props.specificActionIWant();
...

The Provider in react-tunnel puts props into context under the provided namespace and inject pulls them off with the mapProvidedToProps function.

It's not react-redux specific nor really related to redux in any way (and there are probably plenty of other DI type libraries that will get the same job done) but i thought it fit nicely with the react-redux paradigm but would give you the option to use similar semantics deeper in the component tree without bringing along anything specific to redux.

As a final note, you could actually do away wiht the react-redux Provider and just use the react-tunnel provider and inject by doing

// near top of app
<Provider store={mystore}>  //react-tunnel Provider
  {() => <App />}
</Provider>

//when you are going to connect...
@connect(
  stateFn,
  actionFn
)
@inject( provided => ({store: provided.store}) )
export class InjectedThenConnectedComponent...

//the above would have store made available to connect via props and not context but that is now supported in react-redux

anyhow, just some food for thought... would love feedback even if it's why this is a horrible idea.

Thanks,
Josh

Link or router.transitionTo or router.replaceWith doesn't work me

can i do this?

import React from 'react'
import { RouteHandler } from 'react-router'
import { connect } from 'react-redux'
import { setUser } from '../actions/usuarioActions'

@connect()
export default class Root extends React.Component{
  componentDidMount(){
    if(this.props.validate) {
      this.props.dispatch(setUser(this.props.validate))
    }
  }
  render(){
    return (
      <RouteHandler {...this.props} /> 
    )
  }
}

because when i click on Link or use replaceWith from router, just change the url but not the component.

How to integrate with react-router v0.13.3?

So I've been having the hardest time integrating this with React Router. Does anyone have any tips on this? Here is how I am trying to initialize the router now, and it seems to lose the context in the children of the Page component:

Router.run(routes, Router.HistoryLocation, (Handler, state) => {
    React.render(<Provider store={store}>{() => { 
         return <Handler {...state} /> 
    }}</Provider>, document.getElementById('App'));
  });

And here is the warning I get:

Warning: Failed Context Types: Required context `store` was not specified in `Connector`.

Connector only checks state in shouldComponentUpdate

My connector looks like so:

function mapStateToProps(state) {
  const form = state.form;
  return {
    values: form.values,
    errors: form.errors,
    formErrors: form.formformErrors,
    sending: form.sending,
    complete: form.complete || false
  };
}

function mapDispatchToProps(dispatch) {
  return bindActionCreators(formActions, dispatch);
}
export default connect(
  mapStateToProps,
  mapDispatchToProps
)(SignUpForm);

Using the React inspector, I can see that the props of my components are updating when I interact with the form, but child components are not rendering. After debugging, the culprit appears to be with the connector's shouldComponentUpdate method:

Connect.prototype.shouldComponentUpdate = function shouldComponentUpdate(nextProps, nextState) {
     return !_utilsShallowEqual2['default'](this.state, nextState);
};

My state is immutable (and I have tried returning a random object from my reducers to test) and no matter what I can't seem to get this method to return true?

TypeError when requiring react-redux

When requiring react-redux either via Browserify or in the Node REPL, I get the following:

TypeError: Super expression must either be null or a function, not undefined
    at _inherits (/Users/davidnorth/Sites/x/node_modules/react-redux/lib/components/createProvider.js:13:113)
    at /Users/davidnorth/Sites/xxx/node_modules/react-redux/lib/components/createProvider.js:26:5
    at Object.createProvider [as default] (/Users/davidnorth/Sites/x/node_modules/react-redux/lib/components/createProvider.js:70:5)

My version is 0.8.0

Using Wrapped Provider with React.createElement throws TypeError: Object [object Object] has no method 'toUpperCase'

Following the example here
https://github.com/rackt/react-redux#react-router-013
I'm using a wrapped provider on my React Router handler

 <Provider store={store}>
     {() => <Handler {...ReactProps} routerState={routerState} />}
</Provider>

If I pass this to React.renderToString it renders correctly.

if I pass it to React.createElement it throws an error
TypeError: Object [object Object] has no method 'toUpperCase'

site-0 (err): 2015-08-27 01:32 +00:00: TypeError: Object [object Object] has no method 'toUpperCase'
site-0 (err):     at autoGenerateWrapperClass (/opt/site/node_modules/react/lib/ReactDefaultInjection.js:53:19)
site-0 (err):     at Object.getComponentClassForElement (/opt/site/node_modules/react/lib/ReactNativeComponent.js:59:49)
site-0 (err):     at validatePropTypes (/opt/site/node_modules/react/lib/ReactElementValidator.js:361:45)
site-0 (err):     at Object.ReactElementValidator.createElement (/opt/site/node_modules/react/lib/ReactElementValidator.js:408:5)

I'm using some 3rd party middleware that passes the wrapped handler to
React.renderToString(React.createElement())

I suspect this is because React is trying to get a type for the anonymous function {() => }

Do I have to use an anonymous function here? can I wrap it in some other component or something?

actions and dispatch

First at all, thanks for build redux.

I read all discussion on #1 but I still don't get it:

Why Provider/Connection decoration just doesn't bind all actions creator to dispatch only once (willComponentMount or something like that) and pass it (all app actions) to nested component as props?

With the new api proposal, I still have to pass to @connect that actions that I want to use, and its look like to been "re bind" all time that render() is called... I just dont get why.. what have I missed?

specifying local data queries as static properties

Hey there,

Redux is great. You all have done an awesome job finding a simple foundation for lots of things to be built on. I like that I can pretty much do anything I want, while still (theoretically) getting the benefit of everything like various devtools and debugging plugins. Great job!

I've been dwelling the past few days on a few personal customizations that I'm going to use, and I thought you all would be interested in one thing specifically. I'm not pushing for any changes to be integrated here because I know there's been a ton of discussion about the current API. But who knows, maybe you'll like it.

Relay (abstractly, don't know the details yet) does a ton of cool stuff, like data syncing. But there's actually something simple that I really love about it: a component can specify its data dependencies as a simple static property on itself. This "colocation" is really powerful in my opinion.

The current API with @connect is not too far off from something similar: a primitive query that sits close to the component. But first, I don't love decorators, but that's not a huge deal (it's just a function). The main thing that I don't love is having to think about the separation of smart/dumb components.

What I love seeing is this:

const LoggedInUser = React.createClass({
  statics: {
    localQueries: ['currentUser.username']
  },

  render: function() {
    return dom.div({ className: 'item' }, this.props.username);
  }
});

module.exports = connect(LoggedInUser);

The localQueries static property specifies paths into the app state that this component depends on. You can specify as many queries as you like, and they will all be available on props, under the last name in the path. This is just a slight change, it's exactly the same as this:

const LoggedInUser = React.createClass({
 render: function() {
    return dom.div({ className: 'item' }, this.props.username);
  }
});

module.exports = connect(state => {
  username: state.currentUser.username
})(LoggedInUser);

But I think it's easier to read. Also, there's a big opportunity to support other types of queries, like if you use DataScript to store app state in, you could specify DataScript queries.

The other nice thing is you can statically specify actions:

const actions = require('./actions');

const LoggedInUser = React.createClass({
  statics: {
    localQueries: ['currentUser.username'],
    actions: actions,
    namedActions: actions.changeUser
  },

  render: function() {
    // All of the actions are now available on `this.props.actions`, and the `changeUser`
    // action is available on `this.props.changeUser`, and they are bound to the current store
    return dom.div({ className: 'item' }, this.props.username);
  }
});

And my connector will automatically bind them to the current store.

Now, I know you recommend separating smart/dumb components, and the one wrapped by connect would live elsewhere, but personally I think it feels like too much work. I still need to wrap my component with connect, but it doesn't take any parameters, and the query exists on the component itself.

If you want the "dumb" component version of LoggedInUser, it's simply available as LoggedInUser.dumb. My connect wrapper adds it as a static property, so you can use it for testing and stuff.

I created a repo where I'm experimenting with this stuff: https://github.com/jlongster/redux-experiments. Look in "static-queries" and you'll see a demo of this in action. There are links in the README to the main source and a demo of it running.

Note the static-queries-datascript example also. This is the same thing, but demonstrates specifying a DataScript query instead, and using DataScript as the app state instead of JS object.

Sorry that this is a long dump, I thought you might find this interesting though. Feel free to close this issue.

on version >= 0.5 shouldComponentUpdate is not working properly!

Hi,
I have a redux reducers to keep a hash of all users on my app, and I have some react component connect to only one user of this hash. before version 0.5, my connect was:

ps.: I use immutable-js

@connet( (state, props) => {
  return { user: state.users.get( props.userId ) }
})

Now, I cant access props from first method, and need to use 3th method to get correctly user:

@connect(
  s => { return {users: s.users}},
  d => { return {actions: bindActionCreators(actions, d)}},
  (s, d, p) { return {...d, ...p, { user: s.users.get( p.userId)}}} 
)

What happens is that shouldComponentUpdate from connects doesnt see this filter and re render my component all time that ANY users are changed/added/removed

I strong believe that this functions should be binded to connect, and let developer access this.props/this.state from there, or, at least, pass parent props... In my case having this third method is just a overkill

ps.: This issue happens on this example as well:
https://github.com/gaearon/react-redux#inject-todos-of-a-specific-user-depending-on-props-and-inject-propsuserid-into-the-action

Make context-less version of connect

Suggestion: make component wrapped by connect() optionally accept store as a prop.
This may help integration to codebases that don't use React for everything, and can't rely on context.

Alternative API proposals

This API is taken from Redux <Provider>, <Connector>, @provide, @connect.
Right now I don't have examples in this repo but it matches what you've seen in Redux so far.

It's the best we've got now, but I think we can do better!

Common pain points:

  • Not intuitive how way to separate smart and dumb components with <Connector>, @connect
  • You have to manually bind action creators with bindActionCreators helper which some don't like
  • Too much nesting for small examples (<Provider>, <Connector> both need function children)

Let's go wild here. Post your alternative API suggestions.

They should satisfy the following criteria:

  • Some component at the root must hold the store instance. (Akin to <Provider>)
  • It should be possible to connect to state no matter how deep in the tree
  • It should be possible to select the state you're interested in with a select function
  • Smart / dumb components separation needs to be encouraged
  • There should be one obvious way to separate smart / dumb components
  • It should be obvious how to turn your functions into action creators
  • Smart components should probably be able to react to updates to the state in componentDidUpdate
  • Smart components' select function needs to be able to take their props into account
  • Smart component should be able to do something before/after dumb component dispatches an action
  • We should have shouldComponentUpdate wherever we can

Props not passed into connect selector

When this was part of the main redux repo, I could use props in my select functions, because they were passed in a second parameter.

@connect((state, props) => {...}) // props is undefined

This was really useful to select state based on certain props that were passed in (I mostly used it for react router's params and such). It seems like the problem is right here, where only state is being passed: https://github.com/gaearon/react-redux/blob/master/src/components/createConnect.js#L91

Clean before building

Seems like there's an extra file in dist right now because we don't clean before build.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.