gpt4 book ai didi

javascript - 状态更新但不渲染

转载 作者:行者123 更新时间:2023-12-01 02:26:28 25 4
gpt4 key购买 nike

我是 ReactJS 新手,尝试管理状态更改失败。初始状态按预期呈现,状态成功更改,但元素随后不呈现。 DOM 控制台中没有任何错误。我确保在组件类的构造函数中设置初始状态,并且我还尝试绑定(bind)我在构造函数中使用的方法,因为我读到自动绑定(bind)不是 ES6 的一部分。相关组件代码如下:

class MyComponent extends Component {
constructor(props) {
super(props);
this.state = {
myIDs: Array(6).fill('0')
};
this.getMyIDs = this.getMyIDs.bind(this);

};

componentDidMount() {
var ids = this.getMyIDs();
ids.then((result)=> {
this.setState({ myIDs: result }, () => {
console.log(this.state.myIDs)
});
})

};

componentWillUnmount() {
this.setState({
myIDs: Array(6).fill('0')
});
};

getMyIDs() {
return fetch('/api/endpoint').then((response) =>{
return response.json();
}).then((myIDs) => {
return myIDs.result
})
};

render() {
return (
<Tweet tweetId={this.state.myIDs[0]} />
<Tweet tweetId={this.state.myIDs[1]} />
);
}
}

export default MyComponent

更新:正在更新的“元素”是来自react-twitter-widgets的“Tweet”组件。它的来源在这里:

https://github.com/andrewsuzuki/react-twitter-widgets/blob/master/src/components/Tweet.js '

export default class Tweet extends React.Component {
static propTypes = {
tweetId: PropTypes.string.isRequired,
options: PropTypes.object,
onLoad: PropTypes.func,
};

static defaultProps = {
options: {},
onLoad: () => {},
};

shouldComponentUpdate(nextProps) {
const changed = (name) => !isEqual(this.props[name], nextProps[name])
return changed('tweetId') || changed('options')
}

ready = (tw, element, done) => {
const { tweetId, options, onLoad } = this.props

// Options must be cloned since Twitter Widgets modifies it directly
tw.widgets.createTweet(tweetId, element, cloneDeep(options))
.then(() => {
// Widget is loaded
done()
onLoad()
})
}

render() {
return React.createElement(AbstractWidget, { ready: this.ready })
}
}

最佳答案

如 React 文档中所示:

componentWillMount() is invoked just before mounting occurs. It is called before render(), therefore calling setState() synchronously in this method will not trigger an extra rendering. Generally, we recommend using the constructor() instead.

Avoid introducing any side-effects or subscriptions in this method. For those use cases, use componentDidMount() instead.

你不应该在componentWillMount中使用ajax调用在里面调用ajax:componentDidMount

另一件事:你为什么使用componentWillUnmount

该对象将被删除,没有理由在那里进行该调用。

关于javascript - 状态更新但不渲染,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48752417/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com