如何解决将Redux Store连接到列表
我正在尝试将商店连接到后端,但是当我在商店上进行更改时,todoList组件上没有任何更改,这就像redux的基本连接选项不起作用一样。我不知道我在哪里管理日志的问题在哪里可以看到,我相信问题出在连接上,但我不明白为什么。 这是商店。
async function makeGetRequest() {
let res = await axios.get("http://localhost:5000/urls/todos");
let data = await res.data;
initialState.todos = data;
console.log(initialState.todos);
}
let initialState = {
todos: [
{
todo_id: "2345235-2345345-345345",content: "Manger",enable: false,},{
todo_id: "2345235-2345345-345",content: "Dormir",{
todo_id: "2345235-23645-345345",content: "Boire",],};
console.log(initialState.todos);
makeGetRequest();
const rootReducer = (state = initialState,action) => {
return state;
};
export default rootReducer;
console.log()是正常的。 The logs
这是我需要显示的地方。
const todoList = ({ todos }) => {
return (
<div>
<ListGroup>
{todos.map((todo) => {
return (
<div key={todo.todo_id} className="">
<ListGroupItem
className="mt-1 mx-5 text-center rounded-pill inline"
color="success"
>
<h5 className=""> {todo.content}</h5>
<button type="button" className=" btn btn-dark rounded-pill ">
Dark
</button>
</ListGroupItem>
</div>
);
})}
</ListGroup>
</div>
);
};
const mapSateToProps = (state) => {
return {
todos: state.todos,};
};
export default connect(mapSateToProps)(todoList);
,它仅显示硬编码状态。 希望获得帮助
解决方法
您需要在组件安装阶段发出http请求:
const todoList = ({ todos,dispatch }) => {
React.useEffect(() => {
let res = await axios.get("http://localhost:5000/urls/todos");
let data = await res.data;
dispatch({type: 'INIT_DATA',payload: data});
},[]);
return (
<div>
<ListGroup>
{todos.map((todo) => {
return (
<div key={todo.todo_id} className="">
<ListGroupItem
className="mt-1 mx-5 text-center rounded-pill inline"
color="success"
>
<h5 className=""> {todo.content}</h5>
<button type="button" className=" btn btn-dark rounded-pill ">
Dark
</button>
</ListGroupItem>
</div>
);
})}
</ListGroup>
</div>
);
};
并且您需要更换减速器:
const rootReducer = (state = [],action) => {
switch(action.type) {
case 'INIT_DATA': return action.payload;
default: return state;
}
};
这是做您想要的事情的一种简短方法,
但建议将action.type
用作const变量,而不要使用硬编码的字符串。
您还应该制作一个动作文件,然后将其对应用程序中待办事项列表(例如添加项,删除等)的动作分派到存储中。
看看这个:redux basic tutorial
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。