使用RSuite Tree组件:数据已渲染但默认未展开问题
React项目中RSuite Tree组件默认完全展开失效问题
我在React项目中使用RSuite的Tree组件,将接口返回的数组数据构造成树形结构渲染,期望页面加载时树形结构完全展开,方便用户直观查看数据。
项目分为主页面ControlBoardPage和GoalTree组件:
- 主页面通过axios从接口获取目标数据,传递给
GoalTree组件 GoalTree负责将扁平数组转换为树形结构并渲染Tree组件
目前组件已正确组装并渲染数据,但树形结构未默认展开,手动点击后可正常展开。
主页面ControlBoardPage代码
import axios from "axios"; import {createPath, useNavigate, useParams} from "react-router-dom"; import {useEffect, useState} from "react"; // import CopyButton from '../../components/buttons/CopyButton'; import { Form, ButtonToolbar, Button, RadioTile, RadioTileGroup } from 'rsuite'; import { Icon } from '@rsuite/icons'; import PlusIcon from '@rsuite/icons/Plus'; import TrendIcon from '@rsuite/icons/Trend'; import DragableIcon from '@rsuite/icons/Dragable'; import GoalTree from "./GoalTree"; function buildCopyUrl(goalId, endpoint){ return `localhost:3000/${goalId}/${endpoint}`; } function ControlBoardPage() { const { ancestorId, goalId } = useParams(); const [phaseIndex, setPhaseIndex] = useState(0); const [goals, setGoals] = useState([]); const [selectionIndex, setSelectionIndex] = useState(-1); const navigate = useNavigate(); useEffect(() => { const fetchData = async() => { const { data } = await axios.get('http://localhost:3001/ControlBoardPage/getPageData', { params: { "goalId": goalId } }); setGoals(data); } fetchData(); }, []); return ( <> <h3>Control Board</h3> <Form layout="horizontal"> <Form.Group> <GoalTree rawGoals={goals}/> </Form.Group> </Form> </> ) } export default ControlBoardPage;
GoalTree组件代码
import { useState } from "react"; import { Tree } from 'rsuite'; function GoalTree(props){ const { rawGoals } = props; let refinedGoals = [...rawGoals]; refinedGoals.forEach((row) => { row['children'] = []; row['value'] = row.id; row['label'] = row.goal; }) while(refinedGoals.length > 1){ const childGoal = refinedGoals.pop(); for(let i = 0; i < refinedGoals.length; i++){ const isChild = refinedGoals[i].children_ids.includes(childGoal.id); if(isChild){ refinedGoals[i].children.push(childGoal); break; } } } return ( <Tree data={refinedGoals} defaultExpandAll={true}/> ) } export default GoalTree;
已做排查
- 通过调试器检查数据结构,未发现异常
- 在编程社区(r/learnprogramming、Discord)提问,未得到有效解决方案
- 使用ChatGPT4分析,未能解决问题
希望能找出问题根源并解决。
内容的提问来源于stack exchange,提问作者Jackson Ennis
相关产品推荐
相关产品推荐

