[英]mapStateToProps initial value from props, then only state
I have React component that is given some props. 我有一些组件的React组件。 The props are given that a mapStateToProps.
道具被赋予一个mapStateToProps。
const mapStateToProps = (state, {props}) => {
return {
feeds: props.feeds,
feedEntries: props.feedEntries,
....
Once the user starts interacting with the UI, they can change the state. 一旦用户开始与UI交互,他们就可以更改状态。 At this point, the component needs to update itself with
state
not props
. 此时,组件需要使用
state
而非props
更新自身。
const mapStateToProps = (state, {props}) => {
return {
feeds: state.feeds,
feedEntries: state.feedEntries,
....
How do you bootstrap a mapStateToProps
function to first use the props given to the component directly upon first load. 如何自举一个
mapStateToProps
函数,以便在首次加载时直接使用赋予组件的props。 Then following, only state it's data state? 接下来,仅声明其为数据状态?
Use a ternary to check if the state property is undefined
, and take the props
value accordingly: 使用三元检查state属性是否为
undefined
,并相应地获取props
值:
const mapStateToProps = (state = {}, props) => {
return {
feeds: state.feeds === undefined ? props.feeds : state.feeds,
feedEntries: state.feedEntries === undefined ? props.feedEntries : state.feedEntries,
....
If you know that the properties won't have a falsy value (false, null, 0, etc...) as a legitimate value, you can replace the ternary with short-circuit evaluation : 如果您知道属性不会将伪造的值(false,null,0等)作为合法值,则可以将三元数替换为短路评估 :
const mapStateToProps = (state = {}, props) => {
return {
feeds: state.feeds || props.feeds,
feedEntries: state.feedEntries || props.feedEntries,
....
我建议您采取另一种方法,而不是中断mapStateToProps
函数流,而最好从props获取内部值,然后由用户更改的值保存在状态上,您的render函数应支持该状态并检查是否是否收到任何用户数据
Ended up doing the following.. 结束了以下操作。
export default (initProps) => {
const combinedState = {
...defaultState,
...initProps,
};
return createStore(
reducer,
combinedState,
applyMiddleware(logger, thunk),
)
};
Created a function that wraps the createStore function.. which takes an object composed of 1). 创建了一个包装createStore函数..的函数,该函数接受由1)组成的对象。 the props given to the main component (initProps) and 2).
提供给主要组件的道具(initProps)和2)。
defaultProps
— a JS object imported into this file with the default shape of the store, the init props overriding any of the values in defaultProps. defaultProps
—以商店的默认形状导入到此文件中的JS对象,init道具覆盖defaultProps中的任何值。
export default (props) => {
const store = configStore(props);
return (
<Provider store={store}>
<Editor props={{ ...props }} />
</Provider>
)
}
The main component is takes in props, passes those props to the config store function. 主要组件是获取道具,将这些道具传递给config store功能。 The store is built using the combined object above.
使用上面的组合对象构建商店。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.