javascript - 你如何使用 React Hooks 处理外部状态?

标签 javascript reactjs react-hooks

我有一个数学算法,我想将其与 React 分开。 React 将是该算法中状态的 View ,不应定义逻辑在算法中如何流动的方式。此外,由于它是分开的,因此对算法进行单元测试要容易得多。我已经使用类组件(简化)实现了它:

class ShortestPathRenderer extends React.Component {

  ShortestPath shortestPath;

  public constructor(props) {
     this.shortestPath = new ShortestPath(props.spAlgorithm);
     this.state = { version: this.shortestPath.getVersion() };
  }

  render() {
    ... // Render waypoints from shortestPath
  }

  onComponentDidUpdate(prevProps) {
    if (prevProps.spAlgorithm !== this.props.spAlgorithm) {
      this.shortestPath.updateAlgorithm(this.props.spAlgorithm);
    }
  }

  onComponentWillUnmount() {
    this.shortestPath = undefined;
  }

  onAddWayPoint(x) {
    this.shortestPath.addWayPoint(x);
    // Check if we need to rerender
    this.setState({ version: this.shortestPath.getVersion() });
  }
}

我将如何使用 React hooks 来解决这个问题?我正在考虑使用 useReducer 方法。但是,shortestPath 变量将成为 reducer 之外的自由变量,并且 reducer 不再是纯的,我觉得这很脏。所以在这种情况下,算法的整个状态必须随着算法内部状态的每次更新而被复制,并且必须返回一个新的实例,这是不高效的(并且迫使算法的逻辑成为 React-way) :

class ShortestPath {
  ... 
  addWayPoint(x) {
    // Do something
    return ShortestPath.clone(this);
  }
}

const shortestPathReducer = (state, action) => {
   switch (action.type) { 
      case ADD_WAYPOINT:
        return action.state.shortestPath.addWayPoint(action.x);
   }
}

const shortestPathRenderer = (props) => {
   const [shortestPath, dispatch] = useReducer(shortestPathReducer, new ShortestPath(props.spAlgorithm));

   return ...
}

最佳答案

您可以仅使用 useState Hook 在功能模拟示例中基于类切换

function ShortestPathRenderer({ spAlgorithm }) {
  const [shortestPath] = useRef(new ShortestPath(spAlgorithm)); // use ref to store ShortestPath instance
  const [version, setVersion] = useState(shortestPath.current.getVersion()); // state

  const onAddWayPoint = x => {
    shortestPath.current.addWayPoint(x);
    setVersion(shortestPath.current.getVersion());
  }

  useEffect(() => {
    shortestPath.current.updateAlgorithm(spAlgorithm);
  }, [spAlgorithm]);

  // ...
}

关于javascript - 你如何使用 React Hooks 处理外部状态?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58362475/

相关文章:

javascript - jQuery.bind() 和 jQuery.on() 有什么区别?

reactjs - 意外的关键字 'this'

reactjs - React Native - StyleSheet.absoluteFill() 和 StyleSheet.absoluteFillObject() 有什么区别?

javascript - 获取 api 时未调用 useEffect 且未更新状态

javascript - useEffect 调用了两次

javascript - Webpack 只加载 css 引用的图像。不加载js引用的图片

javascript - 有没有更简洁的方法来引用对象的局部变量?

reactjs - 在 Antd Table React 中单独处理分页排序和过滤

javascript - 检查特定父 div 的所有子 div 中的值

javascript - React 中的粘滞条实现?