Я хочу создать счетчик посетителей для своего сайта. Я использую API для получения счетчика посещений. Я хочу создать что-то вроде этого
Я пытаюсь использовать код ниже, но результат такой
Я хочу спросить, что мне нужно сделать, чтобы дизайн стал таким, как я хочу. какой код я сделал неправильно?
function Card(props:any) {
const count = `${props.number}`.split('');
return (
<div style = {{ display: "flex" }}>
{count.map((val) => (
<div
style = {{
fontSize: 42,
marginRight: 10,
background: "#8D0000",
color: "white",
width: 40,
height: 55,
fontWeight: "bold",
textAlign: "center"
}}
>
{val}
</div>
))}
</div>
);
}
const Footer = () => {
const [visitor, setvisitor] = useState<visitortype>();
useEffect(() => {
fetch('https://count.cab/hit/ghG6Oirn0b')
.then(response => response.json())
.then(allvisitor=> console.info(allvisitor))
.catch(error => console.info(error));
}, []);
return (
<GridItem
w = "100%"
h = {{ base: "80px", lg: "300px" }}
colSpan = {{ base: 8, lg: 4 }}
>
<VStack
align = {{ base: "center", lg: "stretch" }}
marginTop = {{ base: "0", lg: "60px" }}
marginLeft = {{ base: "0", lg: "50px" }}
>
<Card number = {visitor?.count}/>
</VStack>
</GridItem>
);
};
Я также пытаюсь использовать Reaction-Flip-Number, но мне все равно не нравится тот стиль, который мне нужен.
<FlipNumbers
height = {25}
width = {20}
color = "white"
background = "#8D0000"
numberStyle = {{
fontSize: 16,
}}
play perspective = {100}
numbers = {`${visitor?.count ?? 0}`}
/>;
Не могли бы вы привести пример, где и как?
Замените setvisitor(allvisitor)
на console.info(allvisitor)
в своем коде. Затем проверьте консоль браузера и пройдите вывод вашего вопроса.
извините, как вставить вывод?
Извините, я имел в виду вставить вывод в ваш вопрос
это результат консоли { "count": 661, "click": 661 }
Извините, я все еще не понимаю, что вы имеете в виду
Поскольку вы получаете доступ к реквизитам в компоненте карты, вам необходимо изменить переменную результата следующим образом:
const result = `${value.value}`.split("");
Если нет, то вам нужно изменить способ доступа к реквизитам и использовать деструктуризацию объектов, например:
const Card = ({value}) => {}
я меняю его, но результат становится неопределенным
Я думаю, согласно журналу, должно быть value.count
или value.click
.
все еще не работает
Я считаю, что ошибка связана с непониманием того, как работает передача параметров компонента. Вы думали, что достаточно просто объявить параметр, передаваемый компоненту. Это не. Компонент получает объект, содержащий все переданные свойства, включая в вашем случае свойство с именем «значение». Итак, если вы продолжите в том же духе, вам будет немного неловко получать доступ к параметру value
из объекта с помощью value.value
.
<Card value = {577} />
// Now "value" is a object, what stored a properties (as "value = {577}" attribute)
const Card = (value) => {
// Now can get "value" attribute from "value" object - not readable
console.info(value.value) // 577
}
В React.js компоненты получают переданные переменные как объект. Вы можете либо объявить объект напрямую (например, как props
) и позже ссылаться на его параметры, либо объявить параметры напрямую, как показано во втором примере.
<Card number = {577} anotherProp = {true} />
function Card(props) {
// Can use properties as parameter of props object
console.info(props.number) // 577
console.info(props.anotherProp) // true
}
// or
function Card({ number, anotherProp }) {
// Can use properties when directly declared them in function
// That's called "Destructuring assignment"
console.info(number) // 577
console.info(anotherProp) // true
}
// Import the React and ReactDOM modules
const { useState, useEffect } = React;
// The component receives the passed values as object (props)
function Card(props) {
const digits = `${props.number}`.split('');
return (
<div style = {{ display: "flex" }}>
{digits.map((val) => (
<div
style = {{
fontSize: 42,
marginRight: 10,
background: "#8D0000",
color: "white",
width: 40,
height: 55,
fontWeight: "bold",
textAlign: "center"
}}
>
{val}
</div>
))}
</div>
);
}
// Instead of declaring the object (props), you can directly declare the parameters within { and }
// That's called "Destructuring assignment"
function AnotherCard({ number }) {
const digits = `${number}`.split('');
return (
<div style = {{ display: "flex" }}>
{digits.map((val) => (
<div
style = {{
fontSize: 42,
marginRight: 10,
background: "#8D0000",
color: "white",
width: 40,
height: 55,
fontWeight: "bold",
textAlign: "center"
}}
>
{val}
</div>
))}
</div>
);
}
// App component
function App() {
return (
<div style = {{ display: "grid", gap: "10px" }}>
Example #1 (Card component with props object)
<Card number = {577} />
Example #2 (AnotherCard component with destructuring assignment)
<AnotherCard number = {688} />
</div>
);
}
// Render the application to the DOM
ReactDOM.render(<App />, document.getElementById("root"));
<script src = "https://cdn.jsdelivr.net/npm/react/umd/react.production.min.js"></script>
<script src = "https://cdn.jsdelivr.net/npm/react-dom/umd/react-dom.production.min.js"></script>
<div id = "root"></div>
// Import the React and ReactDOM modules
const { useState, useEffect } = React;
// The component receives the passed values as object (props)
function Card(props) {
const digits = `${props.number}`.split('');
return (
<div style = {{ display: "flex" }}>
{digits.map((val) => (
<div
style = {{
fontSize: 42,
marginRight: 10,
background: "#8D0000",
color: "white",
width: 40,
height: 55,
fontWeight: "bold",
textAlign: "center"
}}
>
{val}
</div>
))}
</div>
);
}
// Instead of declaring the object (props), you can directly declare the parameters within { and }
// That's called "Destructuring assignment"
function AnotherCard({ number }) {
const digits = `${number}`.split('');
return (
<div style = {{ display: "flex" }}>
{digits.map((val) => (
<div
style = {{
fontSize: 42,
marginRight: 10,
background: "#8D0000",
color: "white",
width: 40,
height: 55,
fontWeight: "bold",
textAlign: "center"
}}
>
{val}
</div>
))}
</div>
);
}
// App component
function App() {
// Declare visitor with default object
const [visitor, setVisitor] = useState({
count: 0,
click: 0
});
// Request data of visitor
useEffect(() => {
fetch('https://count.cab/hit/ghG6Oirn0b')
.then(response => response.json())
.then(v => setVisitor(v));
}, []);
// Will see that the code runs first, and the fetch will update the visitor value asynchronously
console.info(visitor)
return (
<div style = {{ display: "grid", gap: "10px" }}>
Example #1 (Card component with props object)
<Card number = {visitor.count} />
Example #2 (AnotherCard component with destructuring assignment)
<AnotherCard number = {visitor.count} />
</div>
);
}
// Render the application to the DOM
ReactDOM.render(<App />, document.getElementById("root"));
<script src = "https://cdn.jsdelivr.net/npm/react/umd/react.production.min.js"></script>
<script src = "https://cdn.jsdelivr.net/npm/react-dom/umd/react-dom.production.min.js"></script>
<div id = "root"></div>
// Import the React and ReactDOM modules
const { useState, useEffect } = React;
// How many digits in total do we want to display
const DIGIT_COUNT = 5
// The component receives the passed values as object (props)
function Card(props) {
let digits = `${props.number}`.split('');
// Determine the number of digits
const numDigits = digits.length;
// If the number has less than DIGIT_COUNT digits, add leading zeros
if (numDigits < DIGIT_COUNT) {
digits = Array(DIGIT_COUNT - numDigits).fill(0).concat(digits);
}
return (
<div style = {{ display: "flex" }}>
{digits.map((val, index) => (
<div
key = {index}
style = {{
fontSize: 42,
marginRight: 10,
background: "#8D0000",
color: "white",
width: 40,
height: 55,
fontWeight: "bold",
textAlign: "center"
}}
>
{val}
</div>
))}
</div>
);
}
// Instead of declaring the object (props), you can directly declare the parameters within { and }
// That's called "Destructuring assignment"
function AnotherCard({ number }) {
let digits = `${number}`.split('');
// Determine the number of digits
const numDigits = digits.length;
// If the number has less than DIGIT_COUNT digits, add leading zeros
if (numDigits < DIGIT_COUNT) {
digits = Array(DIGIT_COUNT - numDigits).fill(0).concat(digits);
}
return (
<div style = {{ display: "flex" }}>
{digits.map((val, index) => (
<div
key = {index}
style = {{
fontSize: 42,
marginRight: 10,
background: "#8D0000",
color: "white",
width: 40,
height: 55,
fontWeight: "bold",
textAlign: "center"
}}
>
{val}
</div>
))}
</div>
);
}
// App component
function App() {
// Declare visitor with default object
const [visitor, setVisitor] = useState({
count: 0,
click: 0
});
// Request data of visitor
useEffect(() => {
fetch('https://count.cab/hit/ghG6Oirn0b')
.then(response => response.json())
.then(v => setVisitor(v));
}, []);
return (
<div style = {{ display: "grid", gap: "10px" }}>
Example #1 (Card component with props object)
<Card number = {visitor.count} />
Example #2 (AnotherCard component with destructuring assignment)
<AnotherCard number = {visitor.count} />
</div>
);
}
// Render the application to the DOM
ReactDOM.render(<App />, document.getElementById("root"));
<script src = "https://cdn.jsdelivr.net/npm/react/umd/react.production.min.js"></script>
<script src = "https://cdn.jsdelivr.net/npm/react-dom/umd/react-dom.production.min.js"></script>
<div id = "root"></div>
Работает ли это, если данные из API?
Происхождение данных не имеет значения. Просто способ передать его компоненту.
я обновляю свой код выше, но результат все еще не определен, я что-то пропустил?
@ Estherak23 Эстерак23 Ах, я вижу, что предоставленная ссылка на API работает. Нам не нравятся внешние источники в SO, потому что, если они исчезнут, примеры больше не будут работать. Но в конце своего ответа я вставлю код, который работает только с вашим API.
@Estherak23 дополнен двумя примерами (первый: просто получите номер по API, второй: добавьте дополнительные нули)
Обычно это указывает на то, что
val
— это объект, а не строка. Запишите значениеallvisitor
в свойuseEffect
, чтобы убедиться, что у вас правильные данные.