我有一些组件的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等)作为合法值,则可以将三元数替换为short-circuit evaluation:
const mapStateToProps = (state = {}, props) => {
return {
feeds: state.feeds || props.feeds,
feedEntries: state.feedEntries || props.feedEntries,
....
关于javascript - mapStateToProps Prop 的初始值,然后仅状态,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/49835858/