我试图在我的codepen笔中使用React + Redux,但是连接不是注入prop,
也许是因为作为业余爱好者,我错过了一些东西。请看一看。 http://codepen.io/sahil28v/pen/EKEKME?editors=0010
const { Component } = React;
const { createStore, bindActionCreators, applyMiddleWare, combineReducers } = Redux;
const { Provider, connect } = ReactRedux;
const Application = () => (
<div className="ground">
<Tmap />
</div>
);
class Tmap extends Component {
constructor(props){
super(props);
console.log(this.props.mapstate); // This is returning undefined,no idea why
console.log(store.getState().mapstate); // Though this returns val: "hey" as it should properly though.
}
render () {
return (
<div>
</div>
);
}
}
const mapStateToProps = (state) => ({
mapstate: state.mapstate
});
connect(mapStateToProps)(Tmap);
const initialState = {
val: "hey"
}
const mapReducer = (state = initialState, action) => {
return state ;
} ;
const rootReducer = combineReducers({
mapstate: mapReducer,
});
const store = createStore(rootReducer);
React.render(
<Provider store={store}>
<Application />
</Provider>, document.getElementById('app')
);
另外,,,我可以在codepen本身配置存储以使用redux devtools(chrome扩展)。 我试过添加... window.devToolsExtension? window.devToolsExtension():f =&gt; f,到创建商店但不起作用。
当有人回答时 - 您是否也可以推荐好的文档/视频: - &gt;学习ES6 ......
- 感谢您的帮助
答案 0 :(得分:6)
Connect返回我想要的组件的新实例。这可以使用connect作为装饰器。
@connect(
state => ({
mapstate: state.mapstate
})
)
class Tmap extends Component {
constructor(props){
super(props);
alert(this.props.mapstate); // This is returning undefined,no idea why
alert(store.getState().mapstate); //As I understand this is the direct low level api which connect is meant to abstract away along with store.subscribe.
}
render () {
return (
<div>
</div>
);
}
}
答案 1 :(得分:5)
您忘记将连接结果保存到新变量中。而这个新变量就是你应该使用的而不是Tmap。
const CTmap = connect(...
....
<CTmap/>
答案 2 :(得分:1)
请勿导出function
或class
导出connector
类
//don't use export here
function ProductCounterPage(props) {
const {
ProductItem,
OrderItemList,
onCountChange,
...rest
} = props;
...............
}
export default connect(mapStateToProps, null)(ProductCounterPage);
答案 3 :(得分:0)
我遇到了同样的问题,请在下面解决!
首先,您应该导出connect
输出对象,如下所示↓
export default connect(mapStateToProps)(Tmap);
然后,然后在routes
中添加导出的对象而不是类,例如↓
import TmapConnectOutput from './Components/Tmap';
export const routes = <Layout>
<Route exact path='/Tmap' component={TmapConnectOutput as any} />
</Layout>;