【问题标题】:Need to update state on stateless component using react-redux需要使用 react-redux 更新无状态组件的状态
【发布时间】:2019-01-12 22:54:22
【问题描述】:

我有一个使用 react-redux 连接到商店的组件(为简单起见,我缩短了代码):

const Address = (props) => {
    const { userAddresses, removeAddress } = props
    let { showEdit } = props

    return (
        <div>
            {userAddresses.map(address => (
                <div key={address.id}>
                    <p>{address.name}</p>
                    <Button onClick={removeAddress.bind(this, address)}>Delete</Button>
                </div>
            ))}

            <Button
                onClick={() => { showEdit = true }}>
                Add new
            </Button>

            {showEdit ? (
                // show some edit stuff here!!!
            ): null}
        </div>
    )
}

const mapState = state => {
    return {
        userAddresses: state.account.userAddresses,
        showEdit: false
    }
}

const mapDispatch = (dispatch) => {
    return {
        addAddress: address => dispatch(addUserAddress(address)),
        removeAddress: address => dispatch(removeUserAddress(address)),
    }
}

export default connect(mapState, mapDispatch)(Address)

当您单击按钮 (Add new) 时,应该会弹出一个表单(标记为 show some edit stuff here!!!)。我知道如果Address 是一个状态组件,这很容易做到。但是,我需要使用react-redux,据我所知,您必须使用无状态组件才能使用react-redux。谁能指出我正确的方向?

【问题讨论】:

标签: javascript reactjs redux react-redux react-props


【解决方案1】:

不,你确实“必须使用无状态/函数组件”才能使用 React-Redux!

connect 接受类组件和函数组件(甚至像React.memo() 这样的“特殊” React 组件),它们是否在内部使用组件状态(或钩子)并不重要。

另外,作为旁注,您可以简化代码using the "object shorthand" form of mapDispatch

const mapDispatch = {
    addAddress : addUserAddress,
    removeAddress : removeUserAddress
}

(请注意,如果您的道具名称与函数名称相同,则可能会更短。)

【讨论】:

    【解决方案2】:

    保持严格使用 redux,当用户单击按钮时,您应该有另一个动作可以调度。然后,reducer 将更新 showEdit 属性的值,这将导致您的无状态组件重新渲染,从而允许您有条件地渲染编辑表单。

    但是,这是一个信息(编辑表单的可见性与否),对应用程序的其余部分没有用处,因此可能会将您的组件转换为有状态的组件并跟踪 showEdit 中的属性当地的州。

    第三种选择可能是使用 useState 挂钩,但这取决于您项目中的 React 版本,因为它们目前处于 alpha 阶段...

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-04-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-07-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多