我是 React 的新手,我了解 Functional 和 Class 组件以及 Hooks 的概念,例如 useEffect 和 useState;因此,我在将这些知识转化为实践时遇到了麻烦,因为我正在研究以下 React 组件,该组件生成一个普通的 Javascript API 调用,我现在想使用 State 和 Hooks 将其转换为“真正的”React API 调用。
我的问题如下:我想呈现 API 返回的员工对象,从员工的名字和姓氏开始,然后是其他信息。
以纯 Javascript 形式对 API 的请求运行良好并返回所需的数据;因此,我不确定根据定义将状态设置为什么(0?假?别的什么?这取决于什么,我怎么知道?)。
这是代码:
import React, {useEffect, useState} from 'react';
import { Link } from "react-router-dom";
import {
Container,
Row,
Col,
Card,
CardBody,
Table,
Button, Alert, Modal, ModalHeader, ModalBody
} from "reactstrap";
const ContactsList = (props) => {
let request = new XMLHttpRequest()
// Open a new connection, using the GET request …Run Code Online (Sandbox Code Playgroud) javascript reactjs react-state-management react-state react-functional-component
在 ReactJS 中,我正在编写一个无状态组件;
因为我读过避免不必要的状态是最佳实践。
该组件代表一个输入字段,当输入框包含一个值时,它会执行一个函数。
export const InputField = (props) => {
const InputFieldContentsChanged = (event) => {
props.onChange(event.target.value);
};
return (
<div data-component="input-field"
className={(props.value !== "" ? "value": "")}>
<input type={props.type} value={props.value} onChange={InputFieldContentsChanged} />
<span className="bar"></span>
<label>{props.label}</label>
</div>
);
};
InputField.PropTypes = {
type: PropTypes.oneOf([ "text", "password" ]).isRequired,
label: PropTypes.string.isRequired,
value: PropTypes.string,
onChange: PropTypes.func.isRequired
}
Run Code Online (Sandbox Code Playgroud)
现在,我创建了另一个组件,它只是测试上述组件的示例。如下所示:
export const SampleComponent = (props) => {
let componentUsername = "";
const onUsernameChanged = (username) => {
componentUsername = username;
};
return ( …Run Code Online (Sandbox Code Playgroud) reactjs react-hooks react-state react-functional-component react-class-based-component
我如何动态地将数组的名称设置为state,以便从state中获取它。
onCheckBoxItemClickList(e, value, path) {
console.log(e.target.checked)
if (e.target.checked) {
//append to array
this.setState({
[path]: this.state.[path].concat([value])
})
} else {
//remove from array
this.setState({
[path]: this.state.[path].filter(function (val) {
return val !== value
})
})
}
}
Run Code Online (Sandbox Code Playgroud)
我知道如何动态设置和获取状态键,但是当我尝试执行时
[path]: this.state.[path].concat([value])
我收到以下错误:
任何帮助将不胜感激,谢谢
我已经构建了几个模态作为 React 功能组件。它们通过isModalOpen模态关联上下文中的布尔属性显示/隐藏。这非常有效。
Now, for various reasons, a colleague needs me to refactor this code and instead control the visibility of the modal at one level higher. Here's some sample code:
import React, { useState } from 'react';
import Button from 'react-bootstrap/Button';
import { UsersProvider } from '../../../contexts/UsersContext';
import AddUsers from './AddUsers';
const AddUsersLauncher = () => {
const [showModal, setShowModal] = useState(false);
return (
<div>
<UsersProvider>
<Button onClick={() => setShowModal(true)}>Add Users</Button>
{showModal && <AddUsers />}
</UsersProvider>
</div> …Run Code Online (Sandbox Code Playgroud) 我有两个文件 - 其中之一是公共文件,其中包含使用 axios 进行请求的逻辑PUT。progress bar另一个文件包含根据progressEventfrom方法的值进行更新的组件onUploadProgress。我想setUploadPercentage用发出的当前值设置状态。但我很难重构我的代码以访问我的类组件中的这个值FileUpload。任何帮助,将不胜感激。
export function putData(formData) {
return axios.put('/update', formData, {
headers: {
"Content-Type": "multipart/form-data",
},
onUploadProgress : (progressEvent) => {
return parseInt(Math.round((progressEvent.loaded * 100) / progressEvent.total))
},
});
}
Run Code Online (Sandbox Code Playgroud)
import React, { useState } from "react";
import { putData } from "../../services/clientService";
import Progress from "../common/progress";
const FileUpload = () => {
const [uploadPercentage, setUploadPercentage] = useState(0);
const onChange = …Run Code Online (Sandbox Code Playgroud) 在我使用 TypeScript 的 React 应用程序中,我想为组件创建一个上下文。如果未提供默认值,则会createContext显示错误。我想传递的值之一是setFilters钩子调度程序。我应该如何提供默认值?
另外,我不希望它是可选的,以防止!调用。
export interface ContextProps {
filters: FiltersType;
setFilters: React.Dispatch<React.SetStateAction<FiltersType>>;
}
export const MyContext = React.createContext<ContextProps>({
filters: defaultFilters, // imported from constants holder
setFilters: // <---- What should be here?
});
const FiltersContext: React.FC<IProps> = (props: IProps) => {
const [filters, setFilters] = React.useState<FiltersType>(defaultFilters);
return <MyContext.Provider value={{ filters, setFilters }}>{props.children}</MyContext.Provider>;
};
export default FiltersContext;
Run Code Online (Sandbox Code Playgroud) 我有一个反应组件,需要从组件内使用自定义的反应挂钩。
但是,只有在启用功能切换时才应调用此挂钩。我知道这是一种反模式,因为它违反了这里的钩子规则: https: //reactjs.org/docs/hooks-rules.html
所以我的组件文件大致是这样的结构:
const someFeatureToggle = useSomeFeatureToggleHook(React);
const callBackMethod = ()=>{
// doing the logic
}
const someRef1 = React.useRef();
const someOtherRef = React.useRef();
...
There are lots of useState( ) here
return (
JSX
)
Run Code Online (Sandbox Code Playgroud)
对于定制的钩子:
export default function myCustomizedHook(topics, messagesReceivedFn, subscriptionOptions = {}) {
if (!isValidTopics(topics)) {
throw new Error(`Topics arg is invalid - Arg ${JSON.stringify(topics)}`);
}
const [someSubTopics] = useState([topics].flat());
const context = useContext(SomeEventContext);
if (isUndefined(context)) {
throw new Error(`${customizedHook.name} must be used within SomeProvider`); …Run Code Online (Sandbox Code Playgroud) 我正在学习反应。我的代码应该做什么:它应该根据相应行中的星星值来渲染方块。线条具有从 1 到 5 的数字,方块具有从 1 到 5 的星号。如果方块的星号值为 3,则它应该以相同的数字渲染。如果更改星星值,方块应在不同的行中渲染。
下面是我的代码。
import react from "react";
import { useState } from "react";
const squares = [
{'id': 1, 'stars': '5'},
{'id': 2, 'stars': '4'},
{'id': 3, 'stars': '3'},
{'id': 4, 'stars': '3'},
{'id': 5, 'stars': '5'},
{'id': 6, 'stars': '4'},
{'id': 7, 'stars': '2'},
{'id': 8, 'stars': '1'}
]
const lines = [
{'id': 1, 'numberName':'One','number': 1},
{'id': 2, 'numberName':'One','number': 2},
{'id': 3, 'numberName':'One','number': 3},
{'id': 4, 'numberName':'One','number': 4},
{'id': 5, …Run Code Online (Sandbox Code Playgroud) 我有为多个项目呈现的多个按钮。所有按钮都有一个我传递给键的唯一 ID,我试图根据唯一 ID 禁用该按钮。禁用布尔值处于状态,当单击按钮时,我希望它禁用那个唯一的按钮。
但是,我的代码禁用了所有呈现的按钮。
我已经使用 map 来访问我所在州的 park items 数组,因此如果我将它们转换为具有该州唯一键的数组,我不确定如何映射按钮。
这是我到目前为止所拥有的:
我的状态:
this.state = {
parks: [],
todos: [],
disabled: false
};
Run Code Online (Sandbox Code Playgroud)
按钮:
<button
key={item.id} //this id is coming from the mapped array "parks" state
disabled={this.state.disabled}
onClick={() =>
this.setState({
todos: [...this.state.todos, item.name], //this adds the parks
//state items to the todos
//state array
disabled: true
})
}
>
Run Code Online (Sandbox Code Playgroud) 大家好,我刚刚学会了 react,遇到了以下问题:当我在 App.js 中更改 hideFormAdd 时,FormAdd.js 中的 statusForm 只获取第一个未修改的默认值。
//file App.js
<TaskForm open={this.state.hideFormAdd}></TaskForm>
Run Code Online (Sandbox Code Playgroud)
//file FormAdd.js
constructor(props) {
super(props);
this.state = {
statusForm: this.props.open
}
}
Run Code Online (Sandbox Code Playgroud) react-state ×10
reactjs ×10
javascript ×5
react-hooks ×4
arrays ×1
axios ×1
react-class-based-component ×1
react-props ×1
typescript ×1