Redux更新单个元素后数组为空问题,使用react-flow-renderer
问题原因及修复方案
问题定位
你的代码存在3处核心错误,最终导致Redux状态异常、元素被清空:
- 组件props接收错误:
connect注入的updateElement方法存放在组件第一个入参props中,你错误写在了第二个参数位置(该位置为React forwardRef预留),导致调用updateElement时实际执行的是undefined,没有正确触发Redux的dispatch流程。 - 未定义
selectedElement变量:提交表单时直接调用selectedElement.id会抛出引用错误,打断后续逻辑执行。 - Redux状态未同步到ReactFlow组件:你没有将Redux里存储的
elements数组绑定到ReactFlow的elements属性,导致ReactFlow内部状态和Redux状态不一致,出现元素被清空的错觉。
修复代码
1. 修复Node modal组件
import React, { useState } from 'react'; import { connect } from 'react-redux'; import PropTypes from 'prop-types'; import { updateElement } from '../../../../redux/actions/flow'; // 调整参数结构,从props中取出updateElement和selectedElement(selectedElement需由父组件传递) const VPCNodeModal = (props) => { const { updateElement, selectedElement } = props; const [formData, setFormData] = useState({ instance: '', }); const { instance } = formData; const onFormChange = (e) => setFormData({ ...formData, [e.target.name]: e.target.value }); const onSubmitForm = () => { // 增加空值判断避免报错 if (!selectedElement?.id) return; const update = { id: selectedElement.id, options: formData, }; updateElement(update); }; return ( <> <Modal {...props}> <form onSubmit={(e) => { e.preventDefault(); onSubmitForm(); }} > <label> <span> Instance name:</span> <input type='text' name='instance' value={instance} onChange={onFormChange} /> </label> <button type='submit'>Submit</button> </form> </Modal> </> ); }; VPCNodeModal.propTypes = { updateElement: PropTypes.func.isRequired, // 声明selectedElement的类型要求 selectedElement: PropTypes.shape({ id: PropTypes.string.isRequired }) }; export default connect(null, { updateElement })(VPCNodeModal);
2. 同步Redux状态到ReactFlow组件
在你使用ReactFlow的页面组件中,将Redux的elements绑定到组件属性:
// 示例ReactFlow使用代码 import ReactFlow from 'react-flow-renderer'; import { connect } from 'react-redux'; const FlowPage = (props) => { const { elements } = props; // 从Redux取elements return ( <div style={{ height: '100vh' }}> <ReactFlow elements={elements} // 其他你需要的属性 /> </div> ) } const mapStateToProps = (state) => ({ elements: state.flow.elements }) export default connect(mapStateToProps)(FlowPage);
额外校验点
如果修复后仍有问题,请检查:
- 你是否在其他Reducer分支中错误修改了
elements数组,比如错误赋值为空 - 调用
updateElement时传递的payload.id是否和Redux中存储的元素id完全匹配 - 通过Redux调试工具查看
UPDATE_ELEMENTaction触发前后的状态变化,确认action payload是否正确
内容的提问来源于stack exchange,提问作者Oussama Bouchikhi
相关产品推荐
相关产品推荐

