httpコールから応答があったら、ストアを更新するアクションをディスパッチします。コンポーネントにディスパッチするためのアクセスが必要なので、機能を提供するにはmapDispatchToProps
を使用します。
作成者の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"
アクションを処理するレデューサーが必要です。レデューサーはストアを更新し、コンポーネントが接続されていることを考慮して、更新されたストア値を持つ新しい小道具を受け取り、タスクがDOMで更新されます。
EDIT:レデューサーに対処するために、ここに追加の例があります。
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: { }
}
*/
あなたの詳細な答えはカイルですが、私はあなたが私の質問を間違って解釈していると思いますか? タスクをマッピングしたり、ペイロードでアクションを送信したり、Axiosで投稿したりするのに問題はありません。私は、レデューサーからタスクを見つけて更新する方法を理解できません。 – MitchEff