[英]Set local state of component with Redux props given from mapStateToProps()
[英]mapStateToProps initial value from props, then only state
我有一些组件的React组件。 道具被赋予一个mapStateToProps。
const mapStateToProps = (state, {props}) => {
return {
feeds: props.feeds,
feedEntries: props.feedEntries,
....
一旦用户开始与UI交互,他们就可以更改状态。 此时,组件需要使用state
而非props
更新自身。
const mapStateToProps = (state, {props}) => {
return {
feeds: state.feeds,
feedEntries: state.feedEntries,
....
如何自举一个mapStateToProps
函数,以便在首次加载时直接使用赋予组件的props。 接下来,仅声明其为数据状态?
使用三元检查state属性是否为undefined
,并相应地获取props
值:
const mapStateToProps = (state = {}, props) => {
return {
feeds: state.feeds === undefined ? props.feeds : state.feeds,
feedEntries: state.feedEntries === undefined ? props.feedEntries : state.feedEntries,
....
如果您知道属性不会将伪造的值(false,null,0等)作为合法值,则可以将三元数替换为短路评估 :
const mapStateToProps = (state = {}, props) => {
return {
feeds: state.feeds || props.feeds,
feedEntries: state.feedEntries || props.feedEntries,
....
我建议您采取另一种方法,而不是中断mapStateToProps
函数流,而最好从props获取内部值,然后由用户更改的值保存在状态上,您的render函数应支持该状态并检查是否是否收到任何用户数据
结束了以下操作。
export default (initProps) => {
const combinedState = {
...defaultState,
...initProps,
};
return createStore(
reducer,
combinedState,
applyMiddleware(logger, thunk),
)
};
创建了一个包装createStore函数..的函数,该函数接受由1)组成的对象。 提供给主要组件的道具(initProps)和2)。 defaultProps
—以商店的默认形状导入到此文件中的JS对象,init道具覆盖defaultProps中的任何值。
export default (props) => {
const store = configStore(props);
return (
<Provider store={store}>
<Editor props={{ ...props }} />
</Provider>
)
}
主要组件是获取道具,将这些道具传递给config store功能。 使用上面的组合对象构建商店。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.