admin管理员组文章数量:1122832
I'm using react-plotly.js to render a plot in my React application. I have a Zustand store to manage the state of my plot data and layout. When I click a button to fetch new data and update the state, the Plot component does not re-render with the new data. Here is my setup:
store.js
import { create } from 'zustand'
import { immer } from 'zustand/middleware/immer'
const useStore = create(immer((set) => ({
data: [
{
x: [1, 2, 3, 4, 5],
y: [2, 6, 3, 8, 5],
type: 'bar',
marker: { color: 'blue' },
},
],
layout: {
width: 700,
height: 400,
title: 'A Different Plot',
},
setData: (newData) => set((state) => {
console.log("Updating data:", newData);
state.data = newData;
}),
setLayout: (newLayout) => set((state) => {
console.log("Updating layout:", newLayout);
state.layout = newLayout;
}),
})))
export default useStore
App.jsx
import { useEffect } from 'react'
import Plot from 'react-plotly.js'
import useStore from './store'
import './App.css'
function App() {
const data = useStore(state => state.data)
const layout = useStore(state => state.layout)
const setData = useStore(state => state.setData)
const setLayout = useStore(state => state.setLayout)
const fetchData = async () => {
console.log("Fetching data...");
const fakeData = [
{
x: [1, 2, 3, 4, 5],
y: [2, 6, 3, 8, 5],
type: 'bar',
marker: { color: 'blue' },
},
];
const fakeLayout = {
width: 700,
height: 400,
title: 'A Different Plot 5',
};
setData(fakeData);
setLayout(fakeLayout);
console.log("Data fetched and set:", { fakeData, fakeLayout });
};
useEffect(() => {
if (data && layout) {
console.log("Data and layout are ready!");
}
}, [data, layout]);
return (
<>
<button onClick={fetchData}>Load Plot</button>
{data && layout ? (
<Plot key={JSON.stringify({ data, layout })} data={data} layout={layout} />
) : (
<p>Loading...</p>
)}
</>
)
}
export default App
I have tried adding a key prop to the Plot component to force it to re-render, but it still doesn't update with the new data. What am I missing? How can I ensure that the Plot component re-renders when the state changes?
本文标签: reactjsPlotlyjs component not rerendering in React when state changesStack Overflow
版权声明:本文标题:reactjs - Plotly.js component not re-rendering in React when state changes - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1736305911a1932760.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论