React Redux 是一个用于管理 React 应用状态的库。它结合了 React 和 Redux,使得状态管理更加高效和可预测。Redux 是一个独立的状态容器,而 React Redux 提供了连接 React 和 Redux 的工具。
以下是一个简单的示例,展示如何使用 React Redux 提交表单。
首先,确保你已经安装了必要的库:
npm install react-redux redux
创建一个 store.js
文件:
import { createStore } from 'redux';
const initialState = {
formData: {}
};
function reducer(state = initialState, action) {
switch (action.type) {
case 'SUBMIT_FORM':
return { ...state, formData: action.payload };
default:
return state;
}
}
const store = createStore(reducer);
export default store;
创建一个 actions.js
文件:
export const submitForm = (data) => ({
type: 'SUBMIT_FORM',
payload: data
});
创建一个 FormComponent.js
文件:
import React, { useState } from 'react';
import { useDispatch } from 'react-redux';
import { submitForm } from './actions';
const FormComponent = () => {
const [formData, setFormData] = useState({
name: '',
email: ''
});
const dispatch = useDispatch();
const handleChange = (e) => {
const { name, value } = e.target;
setFormData({
...formData,
[name]: value
});
};
const handleSubmit = (e) => {
e.preventDefault();
dispatch(submitForm(formData));
};
return (
<form onSubmit={handleSubmit}>
<input
type="text"
name="name"
value={formData.name}
onChange={handleChange}
placeholder="Name"
/>
<input
type="email"
name="email"
value={formData.email}
onChange={handleChange}
placeholder="Email"
/>
<button type="submit">Submit</button>
</form>
);
};
export default FormComponent;
在 index.js
文件中:
import React from 'react';
import ReactDOM from 'react-dom';
import { Provider } from 'react-redux';
import store from './store';
import FormComponent from './FormComponent';
ReactDOM.render(
<Provider store={store}>
<FormComponent />
</Provider>,
document.getElementById('root')
);
原因:可能是 reducer 没有正确处理 action,或者组件没有正确连接到 Redux store。
解决方法:
SUBMIT_FORM
action。FormComponent
正确使用了 useDispatch
和 useSelector
钩子。确保 FormComponent
使用 useSelector
来读取状态:
import React, { useState } from 'react';
import { useDispatch, useSelector } from 'react-redux';
import { submitForm } from './actions';
const FormComponent = () => {
const [formData, setFormData] = useState({
name: '',
email: ''
});
const dispatch = useDispatch();
const submittedData = useSelector(state => state.formData);
const handleChange = (e) => {
const { name, value } = e.target;
setFormData({
...formData,
[name]: value
});
};
const handleSubmit = (e) => {
e.preventDefault();
dispatch(submitForm(formData));
};
return (
<div>
<form onSubmit={handleSubmit}>
<input
type="text"
name="name"
value={formData.name}
onChange={handleChange}
placeholder="Name"
/>
<input
type="email"
name="email"
value={formData.email}
onChange={handleChange}
placeholder="Email"
/>
<button type="submit">Submit</button>
</form>
<div>
<h3>Submitted Data:</h3>
<p>Name: {submittedData.name}</p>
<p>Email: {submittedData.email}</p>
</div>
</div>
);
};
export default FormComponent;
通过以上步骤,你应该能够成功使用 React Redux 提交表单并管理状态。
领取专属 10元无门槛券
手把手带您无忧上云