[英]Redux is not giving updated state
我是 Redux 的新手。我正在使用 Reactjs、Redux 和 React-flow 制作可視化工作流平台。 用戶可以通過在 Palette 中輸入節點名稱和類型來添加節點(如圖所示右側)。 我將新節點名稱及其類型傳遞給 Redux 調度。 Dispatching and updating the state is working fine (I have checked it by printing it on console), state is updating but I am not getting the updated state automatically just like whenever we update a hook in Reactjs it's changes are shown wherever hook variable is used . 但在這里它不是那樣工作的。 我在中間 div 的頂部打印更新狀態的長度(顯示節點),即使我將新的 object 添加到 state,它也只顯示 0。
我在互聯網上搜索過它,發現在 Redux 中連接 function 會有所幫助,我也實現了它。 但沒有解決辦法。
過去兩天我一直在尋找它,但無法弄清楚問題出在哪里。 如果有人知道問題出在哪里,我錯過了什么/忽略了什么。 請讓我知道,這將是很大的幫助。
Graph.js(我希望 state 自動更新):
import React, { useState, useEffect } from 'react';
import ReactFlow, { Controls, updateEdge, addEdge } from 'react-flow-renderer';
import { useSelector ,connect} from 'react-redux';
import input from '../actions/input';
const initialElements = [
{
id: '1',
type: 'input',
data: { label: 'Node A' },
position: { x: 250, y: 0 },
}]
function Graphs(props) {
const onLoad = (reactFlowInstance) => reactFlowInstance.fitView();
const [elements, setElements] = useState(initialElements);
// const [state,setState]=useState(useSelector(state => state.nodeReducers))
useEffect(() => {
if (props.elements.length) {
console.log("useEffect in", props.elements)
setElements(els => els.push({
id: (els.length + 1).toString(),
type: 'input',
data: props.elements.data,
position: props.elements.position
}));
return;
}
console.log("outside if ",props.elements)
}, [props.elements.length])
const onEdgeUpdate = (oldEdge, newConnection) =>
setElements((els) => updateEdge(oldEdge, newConnection, els));
const onConnect = (params) => setElements((els) => addEdge(params, els));
return (
<ReactFlow
elements={elements}
onLoad={onLoad}
snapToGrid
onEdgeUpdate={onEdgeUpdate}
onConnect={onConnect}
>
{console.log("in main", props.elements)}
<Controls />
<p>hello props {props.elements.length}</p>
</ReactFlow>
)
}
const mapStateToProps=state=>{
return{
elements:state.nodeReducers
}
}
const mapDisptachToProps=dispatch=>{
return{
nodedispatch:()=>dispatch(input())
}
}
export default connect(mapStateToProps,mapDisptachToProps)(Graphs);
nodeReducers.js(減速器):
const nodeReducers=(state=[],action)=>{
switch (action.type) {
case "ADD":
state.push(...state,action.NodeData)
console.log("in node reducers",state)
return state;
default:
return state;
}
}
export default nodeReducers;
input.js(動作):
const input = (obj = {}) => {
console.log("in action",obj)
return {
type: "ADD",
NodeData: {
type: 'input',
data: { label: obj.NodeValue },
position: { x: 250, y: 0 }
}
}
}
export default input;
PaletteDiv.js(我接受用戶輸入的右側調色板 div):
import React, { useState } from 'react'
import '../styles/compoStyles/PaletteDiv.css';
import { makeStyles } from '@material-ui/core/styles';
import { FormControl, TextField, InputLabel, Select, MenuItem, Button } from '@material-ui/core';
import { connect } from 'react-redux';
import input from '../actions/input';
function PaletteDiv(props) {
const [nodename, setNodename] = useState();
const [nodetype, setNodetype] = useState();
const [nodevalue, setNodevalue] = React.useState('');
const handleChange = (event) => {
setNodevalue(event.target.value);
setNodetype(event.target.value);
};
const useStyles = makeStyles((theme) => ({
margin: {
margin: theme.spacing(1),
width: "88%"
},
formControl: {
margin: theme.spacing(1),
minWidth: 120,
},
selectEmpty: {
marginTop: theme.spacing(2),
}
}));
const styles = {
saveb: {
float: "left",
margin: "auto"
},
cancelb: {
float: "right"
},
inputfield: {
display: "block",
width: "100%",
margin: "0"
}
}
const classes = useStyles();
const useStyle = makeStyles(styles);
const css = useStyle();
return (
<div id="myPaletteDiv">
<div className="heading">
<h1>Palette</h1>
</div>
<div className="palette">
<label >WorkFlow Name</label>
<TextField id="outlined-basic" fullwidth className={css.inputfield} variant="outlined" onChange={e => setNodename(e.target.value)} />
<label >Type of Node</label>
<FormControl variant="outlined" className={classes.formControl}>
<InputLabel id="demo-simple-select-outlined-label">Node</InputLabel>
<Select
labelId="demo-simple-select-outlined-label"
id="demo-simple-select-outlined"
value={nodevalue}
onChange={handleChange}
label="Age"
>
<MenuItem value="">
<em>None</em>
</MenuItem>
<MenuItem value={10}>Step</MenuItem>
<MenuItem value={20}>Condition</MenuItem>
</Select>
<Button variant="contained" color="primary" onClick={(e) => {
e.preventDefault();
const node = {
NodeType: nodetype,
NodeValue: nodename
}
props.nodedispatch(node)
console.log("done dispatching")
}}>
Add Node
</Button>
</FormControl>
</div>
</div>
)
}
const mapStateToProps = state => {
return {
elements: state.nodeReducers
}
}
const mapDisptachToProps = dispatch => {
return {
nodedispatch: (node) => dispatch(input(node))
}
}
export default connect(mapStateToProps, mapDisptachToProps)(PaletteDiv);
在這里你可以看到我有一個
標簽在中間 div 的頂部。 它顯示“你好道具 0”。 每當我添加一個節點時,我都希望 0(零)發生變化。
感謝您
敬上,
里沙布·拉格溫德拉
不要將數據直接推送到 state 到 state 中,而是使用擴展運算符重新分配 state
const nodeReducers = (state = [],action) => {
switch (action.type) {
case "ADD":
state = [...state, action.NodeData];
console.log("in node reducers",state);
return state;
default:
return state;
}
}
export default nodeReducers;
這是因為您的減速器必須是純函數。 Reducer 必須與 state 一起使用,就像不可變數據一樣。 你必須避免減速器的副作用
https://redux.js.org/tutorials/fundamentals/part-3-state-actions-reducers#rules-of-reducers
我同意前面的答案,但是,正如我之前所說,在這里我們可以避免像重新評估這樣的副作用:
const nodeReducers = (state = [],action) => {
switch (action.type) {
case "ADD":
return [...state, action.NodeData];
default:
return state;
}
}
export default nodeReducers;
此外,根據最佳實踐,強烈建議將您的操作類型寫入常量,並在您的操作和減速器中使用它們而不是字符串。
// actionTypes.js
export const ADD = "ADD";
// then import it in your reducer and action
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.