我正在学习 React 和 Redux,同时我决定制作带有按钮的网页,点击该按钮会改变状态。在按钮下方,我想在不同的组件中显示当前状态。虽然点击按钮改变了状态,但它并没有反映在组件中。这是我的代码:
应用程序.js
import React from 'react'
import Name from './Name'
import {changeName} from './Action';
export default function App () {
return (
<div>
<button onClick={changeName}>Click me</button>
<Name />
</div>
)
}
名称.js
import React from 'react'
import {store} from './Store'
function Name(props) {
return (
<div>
My name is: {store.getState()}
</div>
)
}
export default Name
商店.js
import { createStore } from 'redux';
import {reducer} from './Reducer';
export const store = createStore(reducer, 'Tarun');
动作.js
import {store} from './Store';
export const changeName = () => {
if (store.getState() === "Tarun"){
store.dispatch({ type: 'name', payload: 'Subhash' });
}
else{
store.dispatch({ type: 'name', payload: 'Tarun' });
}
}
减速器.js
export const reducer = function(state, action) {
if (action.type === 'name') {
return action.payload;
}
return state;
};
当我单击按钮时, Name 组件内的文本不会改变。问题是什么?