一旦您从 http 调用中获得响应,就派发一个更新商店的操作。您需要访问组件中的调度,因此您将使用 mapDispatchToProps 来提供功能。
这里是创建者Dan Abramov 为Redux 编写的一个很棒的入门教程。
此代码示例应该对您有所帮助。
// I'm using this stateless functional component to
// render the presentational view
const Task = ({ label, info }) => (
<div className="task">
<h3{ label }</h3>
<p{ info }</p>
</div>
);
// this is the class that receives props from connect
// and where we render our tasks from
class Tasks extends PureComponent {
// once your component is mounted, get your
// http data and then disptach update action
componentDidMount() {
// using axios here but you can use any http library
axios.post( "/some_url", task )
.then( ( response ) => {
// get update provided by mapDispatchToProps
// and use it to update tasks with response.data
const { update } = this.props;
update( response.data );
})
.catch( ( error ) ) => {
// handle errors
}
}
render() {
// destructure tasks from props
const { tasks } = this.props;
// render tasks from tasks and pass along props
// if there are no tasks in the store, return a loading indicator
return (
<div className="tasks">
{
tasks ? tasks.map(( task ) => {
return <Task
label={ task.label }
info={ task.info }
/>
}) :
<div className="loading">Loading...</div>
}
</div>
);
}
}
// this will provide the Tasks component with props.task
const mapStateToProps = ( state ) => {
return {
tasks: state.tasks
}
}
// this will provide the Tasks component with props.update
const mapDispatchToProps = ( dispatch ) => {
return {
update: ( tasks ) => {
dispatch({
type: "UPDATE_TASKS",
tasks
});
}
}
}
// this connects Task to the store giving it props according to your
// mapStateToProps and mapDispatchToProps functions
export default Task = connect( mapStateToProps, mapDispatchToProps )( Task );
您将需要一个处理"UPDATE_TASK" 操作的reducer。 reducer 更新 store,考虑到组件是连接的,它会收到更新后 store 值的新 props,并且任务会在 DOM 中更新。
编辑:为了解决减速器,这里是一个额外的例子。
import { combineReducers } from "redux";
const tasks = ( state = [], action ) => {
switch( action.type ) {
case "UPDATE_TASKS":
// this will make state.tasks = action.tasks which
// you dispatched from your .then method of the http call
return action.tasks;
default:
return state;
}
};
const other = ( state = {}, action ) => {
...
}
const combinedReducers = combineReducers({
tasks,
other
});
const store = createStore(
combinedReducers/*,
persisted state,
enhancers*/
);
/*
The above setup will produce an initial state tree as follows:
{
tasks: [ ],
other: { }
}
After your http call, when you dispatch the action with the tasks in
the response, your state would look like
{
tasks: [ ...tasks you updated ],
other: { }
}
*/