我有一个使用钩子的React应用程序。我希望将slots
状态在props中传递给其他组件。但是,我的其他组件仅返回undefined
,并且在slots
更改时不会触发道具更改。
应用程序:
import React, { useState, useEffect } from 'react'
import { render } from 'react-dom'
import Pusher from 'pusher-js'
import SlotMachine from './components/SlotMachine'
const App = () => {
const [ slots, setSlots ] = useState({});
const pusher = new Pusher('XXXXXXX', {
cluster: 'xxx',
encrypted: true
});
const channel = pusher.subscribe('my-channel');
channel.bind('my-event', data => {
console.log(`Got data from pusher ${data}`);
setSlots(data);
console.log(data);
});
useEffect(()=>{
console.log(`Slots with channel changes: ${slots}`);
console.log(slots);
**//shows it changes! BUT doesn't seem to actually pass down into props of SlotMachine component**
}, [slots])
return(
<div>
<SlotMachine props={slots}/>
</div>
);
};
render(<App />, document.getElementById('root'));
SlotMachine组件:
import React, { useEffect, useRef, useState } from 'react'
import './slots.css'
function rnd(min, max) {
return Math.floor(Math.random() * (max - min)) + min
}
//slots is a prop as an array of three
//check if slots is empty or if button is clicked
const SlotMachine = (props) => {
const ringElements = useRef();
const [rings, updateRings] = useState([]);
const [manual, buttonClick] = useState(true);
const [ slots, setSlots ] = useState(props.slots);
const slotMap = {
0: 360,
1: 120,
2: 180,
3: 240,
4: 300,
5: 0
};
//shows up as undefined when first renders but doesn't show up ever again
useEffect(() => {
console.log(`props changed: ${props.slots}`)
console.log(props.slots);
}, [props]);
useEffect(()=>{
console.log(`Props Change: ${props.slots}`);
if(props.slots !== undefined ) {
console.log(`API Hit: ${props.slots}`);
buttonClick(false);
setSlots(props.slots);
rotate()
}
}, [props.slots]);
const rotate = () => { ... }, [rings]); //not important rn
useEffect(() => { ... }, [ringElements]);
return(
<div>
<div className="slots">
<div className="rings" ref={ringElements}>
<div className="ring">
<div className="slot" id="0">60</div>
<div className="slot" id="1">120</div>
<div className="slot" id="2">180</div>
<div className="slot" id="3">240</div>
<div className="slot" id="4">300</div>
<div className="slot" id="5">360</div>
</div>
<div className="ring">
<div className="slot" id="0">0</div>
<div className="slot" id="1">1</div>
<div className="slot" id="2">2</div>
<div className="slot" id="3">3</div>
<div className="slot" id="4">3</div>
<div className="slot" id="5">4</div>
</div>
<div className="ring">
<div className="slot" id="0">0</div>
<div className="slot" id="1">1</div>
<div className="slot" id="2">2</div>
<div className="slot" id="3">3</div>
<div className="slot" id="4">3</div>
<div className="slot" id="5">4</div>
</div>
</div>
</div>
<button className="spin-button" onClick={() => { buttonClick(true); rotate();} }>SPIN</button>
</div>
);
}
export default SlotMachine
答案 0 :(得分:2)
您正在传递slots
作为道具props
:
<SlotMachine props={slots}/>
您需要将其传递为slots
:
<SlotMachine slots={slots}/>