我有一个使用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)
当您单击按钮(添加新内容
)时,应该会弹出一个表单(标记为在此处显示一些编辑内容!!!
)。我知道如果 Address
是一个状态组件,这可以很容易地完成。但是,我需要使用 react-redux
,据我所知,您必须使用无状态组件才能使用 react-redux
。谁能指出我正确的方向?
最佳答案
不,你不必“必须使用无状态/函数组件”才能使用 React-Redux!
connect
接受类组件和函数组件(甚至“特殊”React 组件,如 React.memo()
),并且它们是否使用并不重要组件状态(或 Hook )是否位于内部。
此外,作为旁注,您可以简化代码 using the "object shorthand" form of mapDispatch
:
const mapDispatch = {
addAddress : addUserAddress,
removeAddress : removeUserAddress
}
(请注意,如果您的 prop 名称与函数命名相同,则可能会更短。)
关于javascript - 需要使用react-redux更新无状态组件的状态,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54164621/