如何导入改变函数组件(Hooks)状态的函数?



我有一个功能组件,它的状态由钩子使用use state来维护。这个组件实际上使用了很多函数,我想将这些函数存储在另一个文件中并导入它。其中一些函数使用在函数组件中初始化的变量并更改状态。如何在保持模块化的同时实现这个功能?

这是我的代码。如果时间长了,抱歉。我得到的错误- React说我试图在我的功能组件中实例化引用的变量是未定义的。

我正在从NQueensSolution文件导入

我的功能组件

import React, { isValidElement, useState } from 'react'
import Board from './Board';
import './../styling/NQueens.css'
import *  as Solution from './../Solutions/NQueensSolution';

export default function NQueens(){
var rowSet = [];
var colSet = [];
var dx = [-1,1,1,-1];//Direction vectors for checking diagonals, goes NE, SE, SW, NW respectively
var dy = [1,1,-1,-1]; 
const [board, setBoard] = useState([]);  //Our board
const [n, setN] = useState(1);
const [active, setActive] = useState(false);
const [solutions, setSolutions] = useState([]); //Stores all of our solutions to display in the end!

const  dimHandler = (e) =>{   // const means you can change this function 
setN( e.target.value);
console.log(e.target.value);
}
const generateHandler = (e) => {  //Generate the nxn board,
e.preventDefault();  // By default, when pressing a button, the page refreshes, this prevents it
console.log("This is n" + n);
rowSet = new Array(n);  //Initialize row buckets
colSet = new Array(n); //Initialize colBuckets
for(let i = 0; i < n; i++){
rowSet[i] = false;
colSet[i] = false;
}
let row = []; 
let newBoard = [];
for(let i = 0; i < n; i++){
row.push('-');
}
for( let i = 0; i < n; i++){
newBoard.push(row);
}
setBoard( newBoard );
setActive(true);
console.log(board);

}

return (
<div>
<form>
<label>Dimension Of Board:
<input type = "number" name = "dimension" min = "1" max = "8" onChange = {dimHandler} />
<button onClick = { generateHandler}>Generate</button>
</label>
</form>
{active === true? <Board className = "BoardContainer" board = {board} n = {n} /> : null  /*Let's generate the board */ } 
<button onClick = {Solution.solveHandler}>Solve</button>


</div>
)
}

这是我的文件,其中包含我想要导入并在我的功能组件中使用的函数

export {cache, deCache, isValidBounds, canPlace, backTrack,solveHandler};
const cache = (x,y) => {
rowSet[x] = true;
colSet[y] = true;
}
const deCache = (x,y) =>{
rowSet[x] = false;
colSet[y] = false;
}
const isValidBounds = (x,y) =>{ //used to check diagonal bounds
if(x < 0 || x >=n || y < 0 || y>= n ) return false;
return true;
}
const canPlace = (x,y) => {   //essentially valid bounds
if( xSet[x] || ySet[y]) return false;  //Is the row/column occupied?
let xTemp,yTemp;
for( let i = 0 ; i < 4 ;i++){ //Check diagonals
xTemp = dx[i];
yTemp = dy[i];
while( isValidBounds(xTemp,yTemp)){
if(board[xTemp][yTemp] == 'Q') return false;
xTemp += dx[i];
yTemp += dy[i];
}
} 
return true;
}

const backTrack = ( row ) => {
if( row == n ){  //we've found a solution, just return to false to continue our search
solutions.push(board);
return false;
}
for( let i = 0; i< n ; i++){
if(canPlace(x,y)){
board[row][i] = 'Q';
cache(row,i);
if(!backTrack(row + 1)){  //It means our assumption that we had a valid board failed, backtrack
board[row][i] = '-';  //set it back to empty
deCache(row,i);
}
}

}
return false; //We've exhausted all possible placements for our assumption backtrack!!!
}

const solveHandler = () =>{
backTrack(0);
}

晚了,但我相信这是可行的,如果你使用函数声明而不是箭头函数。我看到它们用来改变状态的方式是在你的功能组件的async/await中使用这两个函数(例如:cache和setBoard),这样你就可以通过传递参数。

最新更新