【发布时间】:2023-02-25 13:32:44
【问题描述】:
我说要学习 React 和 Redux,但我无法弄清楚为什么我的 React 组件在 Redux 存储状态更改后不会重新呈现。
这是我的代码:
const initialState = { value: 'Loading...' }
function onSetName(state = initialState, action) {
if (action.type === 'doc/docnamechanged') {
return {
...state,
value: action.payload
}
}
return state
}
export const setName = text => {
return {
type: 'doc/docnamechanged',
payload: text
}
}
export const store = configureStore({ reducer: onSetName })
store.subscribe(() => Layout(), App());
export default function App() {
return (
<Routes>
<Route element={<Layout />}>
<Route path="/1" element={<PublicPage />} />
</Route>
</Routes>
)
}
那是我的派遣
if (store.getState().value != "AD") {
store.dispatch(setName("AD"));
}
function Layout() {
console.log(store.getState().value);
const name = store.getState().value;
return (
<div className="App">
<div className="header">
<img className="logo" src="images/logotype.png" alt="logo" />
<div className="UpperTitle">
{name}
</div>
</div>
</div>
)
}
所以我可以在控制台中看到 store.getState().value 确实发生了变化,但在呈现的 <div className="UpperTitle"> {name} 中没有变化。如您所见,我也尝试订阅我的 App() 函数,但这根本没有帮助。感谢任何帮助。
如果我在 index.js 中订阅 render(),我设法让它以某种方式工作,但这似乎是错误的并导致警告消息
react-dom.development.js:86 Warning: Render methods should be a pure function of props and state; triggering nested component updates from render is not allowed. If necessary, trigger nested updates in componentDidUpdate.
【问题讨论】:
标签: javascript reactjs react-redux